본문 바로가기
Study/Java

[Java] 예외처리 Exception, Error (이것만 알면 된다!!)

by JYHAN 2020. 7. 4.

예외란?

프로그램에 문제가 있는 것을 말하며, 예외로 인해 시스템 동작이 멈추는 것을 막는 것을 '예외처리'라고 한다

 

Exception - Error는 개발자가 대처할 수 있음

Error - Error는 개발자가 대처할 수 없음 (ex: 물리적인 에러)

 

Exception

  • Checked Exception: '예외처리'를 반드시 해야 하는 경우(네트워크, 파일 시스템 등)
  • Unchecked Exception: '예외처리'를 개발자의 판단에 맞기는 경우(데이터 오류 등)

Tip) Exception Handling 두개만 구분할 줄 알면 된다

1. RuntimeException: 예외처리를 하지 않는다 // How to? 로직으로 처리한다. 즉, 에러가 안나게끔 막아라!

String name = null;
System.out.println("문자열의 길이: "+name.length()); // NullPointException 발생

String name = null;
if(name!=null)
	System.out.println("문자열의 길이: "+name.length());
else
	System.out.println("문자열의 길이: "+0); // 0

2. None-RuntimeException: 반드시 예외처리를 한다 // How to? 예외처리를 한다. 하지 않으면 컴파일 에러 발생!!

throws
try{

}catch(){

}finally{

}

Exception 클래스

Exception 클래스 하위 클래스로 NullPointerException, NumberFormatException 등이 있다

Exception 클래스 하위 클래스 종류

  • NullPointerException : 객체를 가리키지 않고 있는 레퍼런스를 사용할 때
  • ArrayIndexOutOfBoundException : 배열에서 존재하지 않는 인덱스를 가리킬 때
  • NumberFormatException : 숫자 데이터에 문자 데이터 등을 넣었을 때

try ~ catch

개발자가 예외처리하기 가장 쉽고, 많이 사용되는 방법이다

try{
	예외가 발생할 수 있는 코드
}catch (Exception e){
	예외가 발생했을 때 처리할 코드
}
public class MainClass {
	public static void main(String[] args) {
		int i = 10;
		int j = 0;
		int r = 0;
		
		System.out.println("Before Exception");
		
		try {
			r = i / j;
		}catch(Exception e) {
			e.printStackTrace();
			String msg = e.getMessage();
			System.out.println("Exception: "+msg);			
		}
		
		System.out.println("After Exception");
	}
}

---- result ----
Before Exception
java.lang.ArithmeticException: / by zero
	at com.java.exception.MainClass.main(MainClass.java:12)
Exception: / by zero
After Exception

 

다양한 예외처리

Exception 및 하위 클래스를 이용해서 예외처리를 다양하게 할 수 있다

 

finally

public class MainClass {
	public static void main(String[] args) {
		int i = 10;
		int j = 0;
		int r = 0;
		
		System.out.println("Before Exception");
		
		try {
			r = i / j;
		}catch(Exception e) {
			e.printStackTrace();
			String msg = e.getMessage();
			System.out.println("Exception: "+msg);			
		} finally {
			System.out.println("예외 발생 여부에 상관없이 언제나 실행");
		}
		System.out.println("After Exception");
	}
}

---- result ----
Before Exception
java.lang.ArithmeticException: / by zero
	at com.java.exception.MainClass.main(MainClass.java:12)
Exception: / by zero
예외 발생 여부에 상관없이 언제나 실행
After Exception

 

throws

예외 발생 시 예외 처리를 직접 하지 않고 호출한 곳으로 넘긴다

public class MainClass {
	public void firstMethod() throws Exception{
		secondMethod();
	}
	public void secondMethod() throws Exception{
		thirdMethod();
	}
	public void thirdMethod() throws Exception{
		System.out.println("10 / 0 = "+(10 / 0 ));
	}
	public static void main(String[] args) {
		MainClass mc = new MainClass();
		try {
			mc.thirdMethod();
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			System.out.println("예외와 상관없이 언제나 실행");
		}
	}
}

---- result ----
java.lang.ArithmeticException: / by zero
	at com.java.exception.MainClass.thirdMethod(MainClass.java:11)
	at com.java.exception.MainClass.main(MainClass.java:16)
예외와 상관없이 언제나 실행

 

'Study > Java' 카테고리의 다른 글

[Java] 네트워킹 (Socket, 양방향 통신)  (0) 2020.07.04
[Java] 입력과 출력  (0) 2020.07.04
[Java] Collections  (0) 2020.07.03
[Java] 문자열 클래스(String, StringBuilder, StringBuffer)  (0) 2020.07.03
[Java] Lambda 람다식  (0) 2020.07.03

댓글