예외는 에러라고 할 수 있다. 하지만 정확히 말하면 에러는 하드웨어의 오작동이나 고장으로 인해 응용프로그램 실행 오류가 발생하는 것을 말한다.
예외는 이런 에러 이외에 프로그램 자체에서 발생하는 오류이다. 사용자의 잘못된 조작이나 개발자의 잘못된 코딩으로 인해 발생하는 프로그램 오류를 말한다.
예외가 발생하면 정상적으로 실행하거나 종료할 수 있도록 예외 처리를 해야 한다. 예외 처리는 try ~ catch, finally, throws를 사용한다.
예외처리 전
package oop0916;
public class Test01_exception {
public static void main(String[] args) {
//1) 예외처리 하지 않은 경우
System.out.println(1);
//Exception이 발생되면 프로그램은 정상적으로 종료되지 않음
System.out.println(3/0); //ArithmeticException 발생
System.out.println(5);
System.out.println("END");
}//main() end
}//class end
위의 경우 다음과 같은 메시지가 나온다.
4줄이 전부 출력되지 않고 예외가 발생하기 전 코드까지만 출력이 된다.
예외처리 후
package oop0916;
public class Test01_exception {
public static void main(String[] args) {
//2)예외처리를 한 경우
//-> Exception이 발생하더라도 정상적으로 프로그램은 종료시킬 수 있다
try {
//예외 발생이 예상되는 코드 작성
System.out.println(1);
System.out.println(3/0);
System.out.println(5);
} catch(ArithmeticException e) {
//예외가 발생되었을 때 처리할 코드 작성
System.out.println(e);
}//end
System.out.println("END");
}//main() end
}//class end
코드가 실행되다가 예외를 만나면 catch로 이동해 그 이후 코드들이 실행된다. catch의 ( ) 부분에는 예외 클래스와 변수를 작성한다.
많이 발생하는 예외들
ArrayIndexOutOfBoundsException
배열에서 인덱스 범위를 초과할 경우 발생하는 예외이다.
try {
System.out.println(1);
int[] num = new int[3];
num[5] = 2;
System.out.println(7);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}//end
NumberFormatException
숫자로 변환할 수 없는 문자가 있을 경우 발생하는 예외이다.
try {
System.out.println(1);
int num = Integer.parseInt("KOREA");
} catch (NumberFormatException e) {
System.out.println(e);
}//end
NullPointerException
null값을 갖는 참조 변수를 사용했을 때 발생한다.
try {
System.out.println(1);
Integer inte = null;
System.out.println(5/inte);
} catch (NullPointerException e) {
System.out.println(e);
}//end
다중 catch
try {
int a = 2/0;
int b = Integer.parseInt("KOREA");
int[] num = new int[3];
num[5] = 7;
} catch (ArithmeticException e) {
System.out.println(e);
} catch (NumberFormatException e) {
System.out.println(e);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
} catch (NullPointerException e) {
System.out.println(e);
}//end
try 내부에서 다양한 예외가 발생할 수 있다. 이 때 다중 catch를 사용하여 예외 별로 예외 처리를 다르게 할 수 있다. catch 블록이 여러 개라도 한 번에 하나 씩만 실행된다. 예외가 동시다발적으로 발생하는 것이 아니라 하나 발생하면 멈추고 해당 catch 블록으로 이동하기 때문이다.
catch 블록을 작성할 때는 순서에 유의해야 한다. 상위 예외 클래스를 하위 예외 클래스보다 아래에 작성해야 한다. 예외를 처리해줄 catch 블록은 위에서부터 검색되기 때문에 상위 예외 클래스가 하위보다 위에 있다면 하위 예외 클래스 catch 블록은 실행되지 않기 때문이다.
try {
int a = 2/0;
int b = Integer.parseInt("KOREA");
int[] num = new int[3];
num[5] = 7;
} catch (Exception e) { //다형성
//Exception 클래스 : 모든 예외 발생의 조상 클래스
System.out.println(e);
}//end
Exception은 모든 예외 클래스의 상위 클래스이다. 따라서 어떤 예외인지 구체적으로 알지 못할 때 Exception을 사용해도 예외 처리가 된다.
finally
//-> 예외가 발생하거나, 발생하지 않더라도 무조건 실행
try {
System.out.println("OPEN");
System.out.println(1/0);
} catch (Exception e) {
System.out.println(e);
} finally {
System.out.println("CLOSE");
}//end
finall은 예외 발생 여부와 상관없이 항상 실행할 내용이 있을 때만 사용한다. 따라서 생략이 가능하다.
'웹개발 교육 > Java' 카테고리의 다른 글
[36일] Java (44) - List (0) | 2022.09.16 |
---|---|
[36일] Java (43) - throws (0) | 2022.09.16 |
[35일] Java (41) - 내부 클래스(중첩 클래스) (0) | 2022.09.15 |
[35일] Java (40) - 익명 객체 (0) | 2022.09.15 |
[35일] Java (39) - interface (0) | 2022.09.15 |