Exception 정의
프로그램 실행 중 예기치 못한 사건을 예외라고 한다. 예외 상황을 미리 예측하고 처리할 수 있는데, 이렇게 하는 것을 예외처리라고 한다.
대표적인 Exception, ArithmeticException 예시
public class ExceptionExam{
public static void main(String[] args){
int i = 10;
int j = 0;
int k = i / j;
System.out.println(k);
System.out.println(main 종료!!);
}
}
예외처리 이유
프로그래머는 j라는 변수에 0이 들어올지도 모르는 예외 상황을 미리 예측하고 처리할 수 있다.
예외처리 문법
public class ExceptionExam{
public static void main(String[] args){
int i = 10;
int j = 0;
try{
int k = i / j;
}catch(ArithmeticException e){ // ArithmeticException 라는 예외 객체를 e 라는 참조변수가 가르키고 있음
System.out.println("0으로 나눌 수 없습니다. : " + e.toString()); // e라는 참조변수는 toString이라는 메소드를 가지고 있음
}finally{
System.out.println("무조건 실행되는 블록");
}
}
}
실행결과
0으로 나눌 수 없습니다.: java.lang.ArithmeticException: / by zero
무조건 실행되는 블록
Exception관한 부가 설명