예외가 발생했을 때 예외를 호출한 쪽에서 처리하도록 던져준다.
// 정수를 매개변수로 2개를 받아들인 후 나눗셈을 한 후 그 결과를 반환하는 divide 메소드정의, main 메소드에서는 divide 메소드를 호출
public class ExceptionExam2{
public static void main(String[] args){
int i = 10;
int j = 0;
int k = divide(i, j);
System.out.println(k);
}
public static int divide(int i, int j){
int k = i / j;
return k;
}
}
throws 포함하게끔 수정 후
// 메소드를 호출한 쪽에서 예외 처리하도록 divide 메소드 throws로 수정
public class ExceptionExam2{
public static void main(String[] args){
int i = 10;
int j = 0;
int k = divide(i, j);
System.out.println(k);
}
public static int divide(int i, int j) throws ArithmeticException{
int k = i / j;
return k;
}
}
try-catch 구문 포함하게끔 수정 후
// divide 메소드를 호출한 쪽에서 예외처리 할 수 있도록 try-catch 문 추가
public class ExceptionExam2{
public static void main(String[] args){
int i = 10;
int j = 0;
try{
int k = divide(i, j);
System.out.println(k);
}catch(ArithmeticException e){
System.out.println("0으로 나눌 수 없음");
}
}
public static int divide(int i, int j) throws ArithmeticException{
int k = i / j;
return k;
}
}
throw는 오류를 떠넘기는 throws와 보통 같이 사용된다.
public class ExceptionExam3{
public static void main(String[] args){
int i = 10;
int j = 0;
int k = divide(i, j);
System.out.println(k);
}
public static int divide(int i, int j) throws IllegalArgumentException{
if(j == 0){
// 새로운 Exception 객체를 통해 오류 발생시키기
throw new IllegalArgumentException("0으로 나눌 수 없어요");
}
int k = i / j;
return k;
}
}
실행결과(에러발생)
Exception in thread "main" java.lang.IllegalArgumentException: 0으로 나눌 수 없어요.
at first/first.HelloWorld.divide(HelloWorld.java:13)
at first/first.HelloWorld.main(HelloWorld.java:7)
j가 0일 경우에 new 연산자를 통해 IllegalArgumentException 객체가 만들어진다.
new 앞에 throw는 해당 라인에서 익셉션이 발생한다는 의미이다.
즉 그 줄에서 오류가 발생했다는 것이다. 0으로 나눌 수 없습니다. 라는 오류가 발생한 것이다.
Exception 클래스 이름을 보면 Argument가 잘못되었기 때문에 발생한 오류라는 것을 알 수 있다.
에러도 발생하지 않고, 올바르지 않은 결과를 리턴하지 않도록 수정
public class ExceptionExam3{
public static void main(String[] args){
int i = 10;
int j = 0;
try{
int k = divide(i, j);
System.out.println(k);
}catch(IllegalArgumentException e){
System.out.println("0으로 나누면 안 됨");
}
}
public static int divide(int i, int j) throws IllegalArgumentException{
if(j == 0){
throw new IllegalArgumentException("0으로 나눌 수 없어요");
}
int k = i / j;
return k;
}
}