java
throws 명령어와 예외 처리 방법 두가지
easy16
2019. 9. 15. 17:31
ex1) exception handle
public static void main(String [] args) { TestApplication test = new TestApplication(); test.A(); } private void A() { B(); } private void B() { //2, 넘어온 Exception을 try-catch 처리 해 준다. try { C(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void C() throws Exception { //1,throws를 통해 호출하는 메소드로 exception handling을 미룬다. throwable(); } private void throwable() throws Exception { throw new Exception("I'm exception!"); }
ex2) Runtime exception의 경우, 명시적으로 throws를 사용하지 않아도 문제가 되지 않는다.
public static void main(String [] args) { TestApplication test = new TestApplication(); test.A(); } private void A() { B(); } private void B() { //2, 넘어온 Exception을 try-catch 처리 해 준다. try { C(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void C() /* throws RuntimeException */ { //1,throws를 통해 호출하는 메소드로 exception handling을 미룬다. throwable(); } private void throwable() throws RuntimeException { throw new RuntimeException("I'm exception!"); }
출처 : 자바의 신