try 블록에는 예외가 발생할 가능성이 있는 코드를 작성하고 try 블록 안에서 예외가 발생하는 경우 catch 블록이 수행됨.
try {
예외가 발생할 수 있는 코드 부분
} catch(처리할 예외 타입 e) {
try 블록 안에서 예외가 발생했을 때 예외를 처리하는 부분
}
프로그래머가 예외를 처리해 줘야 하는 예 (배열의 오류 처리)
publicclassArrayIndexException2 {
publicstaticvoidmain(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
try {
for (inti = 0; i <= 5; i++) { // index 5가 없기 때문에 오류가 남.System.out.println(arr[i]);
}
} catch (ArrayIndexOutOfBoundsExceptione) { // ArrayIndexOutOfBoundsException 클래스를 활용System.out.println(e.getMessage());
System.out.println(e);
}
System.out.println("here"); // 예외 처리를 했기 때문에 해당 출력문은 출력이 된다.// 결과// 1// 2// 3// 4// 5// Index 5 out of bounds for length 5// java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5// here
}
}
try-catch-finally 문
finally 블록에서 파일을 닫거나 네트워크를 닫는 등의 리소스 해제 구현을 함.
try{} 블록이 수행되는 경우, finally{} 블록은 항상 수행됨.
여러 개의 예외 블록이 있는 경우 각각에서 리소스를 해제하지 않고 finally 블록에서 해제하도록 구현함.
예외 처리는 예외가 발생하는 문장에서 try-catch 블록으로 처리하는 방법과 이를 사용하는 부분에서 처리하는 방법 두 가지가 있음.
throws를 이용하면 예외가 발생할 수 있는 부분을 사용하는 문장에서 예외를 처리할 수 있음.
하나의 try{} 블록에서 예외가 여러 개 발생하는 경우
여러 개의 예외가 발생하는 경우 예외를 묶어서 하나의 방법으로 처리할 수도 있고,
try {
test.loadClass("a2.txt", "java.lang.Stringgggggg");
} catch (FileNotFoundException | ClassNotFoundExceptione) { // 여러 개의 예외가 발생하는 경우 예외들을 묶어서 하나의 방법으로 처리System.out.println(e);
} catch (Exceptione) {
System.out.println(e);
}
각각의 예외를 따로 처리할 수도 있음
try {
test.loadClass("a2.txt", "java.lang.Stringgggggg");
} catch (FileNotFoundExceptione) {
System.out.println(e);
} catch (ClassNotFoundExceptione) {
System.out.println(e);
} catch (Exceptione) { // 위 두 개의 exception 처리 말고도 어떤 오류가 발생될지 모를 때에는 Exception가 최상위 클래스이기 때문에 Exception 클래스로 받아서 처리하여도 된다.System.out.println(e);
}
Exception 클래스를 활용하여 default 처리를 할 때 Exception 블록은 맨 마지막에 위치해야 함.
java_exception--try-catch-finally----throws's People