Exception
프로그램실행중 예기치 못한 사건을 예외라고 한다. 예외 상황을 미리 예측하고 처리할 수 있는데, 이렇게 하는 것을 예외 처리라고 한다.
why? use it
ExceptionExam.java
public class ExceptionExam {
public static void main(String[] args) {
int i = 10;
int j = 0;
int k = i/j;
System.out.println(k);
}
}
>>> 이렇게 0 으로 나눌려고하니 program end
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionExam.main(ExceptionExam.java:7)
Process finished with exit code 1
code
try - catch - finally
try { ...
// exception 가능성이 있는 block
} catch ( exception class name ) {
// exception 처리 block
// 여러개의 catch 를 써도 됨.
// 어떤 exception 일지 모를때는 , Exception 을 쓰면 됨.
} finally {
// must , make sure 실행되는 blcok
// 쓰지 않아도 됨.
}
use it
public class ExceptionExam {
public static void main(String[] args) {
int i = 10;
int j = 0;
try {
int k = i/j;
System.out.println(k);
} catch (ArithmeticException e) {
System.out.println(" Can't divide into 0 it"+e.toString());
}
}
}
catch (ArithmeticException exname) {
// exception class variable name : exname
System.out.println(" Can't divide into 0 it"+exname.toString();
// .toStrig() - exception's information 을 알려줌
}
.toStrig() - exception's information 을 알려줌
>>>
Can't divide into 0 it : java.lang.ArithmeticException: / by zero