웹개발 교육/Java
[36일] Java (43) - throws
ewok
2022. 9. 16. 13:02
예외가 발생할 수 있는 코드를 작성할 때 try ~ catch를 사용할 수 있지만, throws를 사용하여 메소드를 호출한 곳으로 예외를 떠넘길 수 있다.
//throws를 이용한 예외처리
public void view() throws Exception {
int a = 3/0;
}//view() end
public void disp() throws NullPointerException, NumberFormatException{
int a = Integer.parseInt("KOREA");
}//disp() end
public class Test02_throws {
public static void main(String[] args) {
// throws문
//-> 메소드 호출 시 예외처리를 한꺼번에 모아서 처리
try {
Test test = new Test();
test.view();
test.disp();
} catch (Exception e) {
System.out.println(e);
}//end
}//main() end
}//class end
throws가 붙어 있는 메소드는 반드시 try 블록 내에서 호출되어야 한다. 그리고 예외가 catch 블록에서 처리가 된다.