자바/8. 예외처리
Java 06 예외의 발생과 catch문
스펀지연구소
2021. 4. 1. 18:01
예외가 발생하면, 발생한 예외클래스의 인스턴스가 만들어 진다.
ex) ArithmeticException이 발생하면 ArithmeticException 인스턴스가 생성된다.
첫 번째 catch문부터 차례로 내려가면서 catch문 괄호( ) 내에 선언된 참조변수의 종류와 생성된 예외클래스의 인스턴스에 instanceof 연산자를 이용해서 검사하며, 검사결과가 true인 catch문을 만날 때까지 계속 검사한다.
package ch08;
public class Ex_8_3 {
public static void main(String[] args) {
System.out.println(1);
System.out.println(2);
try {
System.out.println(3);
System.out.println(0/0);
System.out.println(4); // 실행되지 않는다.
} catch(Exception e) { // ArithmeticException대신 Exception을 사용
System.out.println(5);
} // try-catch문의 끝
System.out.println(6);
} // main 메서드의 끝
}
Exception은 모든 예외의 조상이니까 ArithmeticException 대신에 사용할 수 있다.
package ch08;
public class Ex_8_4 {
public static void main(String[] args) {
System.out.println(1);
System.out.println(2);
try {
System.out.println(3);
System.out.println(0/0); //ArithmeticException 발생시킴
System.out.println(4); // 실행되지 않는다.
}catch (ArithmeticException ae) { // catch문 실행
if(ae instanceof ArithmeticException)
System.out.println("true");
System.out.println("ArithmeticException");
}catch (Exception e) { // ArithmeticException을 제외한 모든 예외
System.out.println("Exception");
} // try-catch 문의 끝
System.out.println(6);
} // main 메소드의 끝
}