예외
란 정상적이지 않은 Case 를 말한다.
예를 들어, 아래와 같은 Case 들이 있다.
/* 0 으로 나누기 */
int a = 5 / 0; // Error: ArithmeticException 을 출력한다.
/* 배열 index 초과 */
int[] b = new int[3];
System.out.println(a[3]); // Error: ArrayIndexOutOfBoundsException 을 출력한다.
/* 없는 파일 열기 */
BufferedReader br = new BufferedReader(new FileReader("./memo.txt")); // Error: FileNotFoundException 을 출력한다.
정상적이지 않은 Case 에 대한 적절한 처리 방법을 말한다.
try {
/* 시도해보고 */
/* 조건에 따라 예외 Case 를 던지고 */
} catch (/* 예외 Case 를 받아서 */ ) {
/* 예외 Case 를 받을 경우, 이러한 명령어를 실행하라 */
} finally {
/* 예외랑 상관없이 늘 명령어를 실행하라 */
}
class NotTenException extends RuntimeException {} // RuntimeException 을 상속받으면 해당 클래스는 예외로 공식적인(?) 인정을 받아 출력 시 Error 메세지를 띄우게 된다.
public class Test {
public static void main(String[] args) {
int ten = 0;
if (ten != 10) {
throw new NotTenException(); // Error: NotTenException
}
}
}
아래처럼 동일한 스코프 내에서 throw new NotTenException();
아래에 다른 코드가 기입되는 경우, Unreachable Statement 라는 에러가 뜬다.
class NotTenException extends RuntimeException {}
public class Test {
public static void main(String[] args) {
int ten = 0;
if (ten != 10) {
throw new NotTenException();
ten = 10; // Error: Unreachable Statement
}
}
}
이유는 위와 같은 에러가 뜨는 이유 에서 After a throw statement 를 참고하자.
package memorize;
import java.io.IOException;
class NotTenException extends RuntimeException {}
public class Test {
public static boolean checkTen(int ten) {
if (ten != 10) {
return false;
}
return true;
}
public static boolean checkTenWithException(int ten) {
try {
if (ten != 10) {
throw new NotTenException();
}
} catch (NotTenException e) {
System.out.println(e);
return false;
}
return true;
}
public static boolean checkTenWithThrows(int ten) throws NotTenException {
if (ten != 10) {
throw new NotTenException();
}
return true;
}
public static void main(String[] args) throws IOException {
boolean checkResult = true;
/* 예외처리 없이 */
checkResult = checkTen(10);
System.out.println(checkResult); // true
checkResult = checkTen(9);
System.out.println(checkResult); // false
/* throw: 메서드 내부에서 예외 처리를 한다. */
checkResult = checkTenWithException(10);
System.out.println(checkResult); // true
checkResult = checkTenWithException(9);
System.out.println(checkResult); // memorize.NotTenException
// false
boolean checkResult2 = false;
/* throws: 메서드를 호출한 곳에서 예외 처리하도록 떠넘긴다 -> 예외를 전가받은 곳에서 try-catch 문을 작성해준다. */
try {
checkResult2 = checkTenWithThrows(9);
} catch (NotTenException e) {
System.out.println(e); // memorize.NotTenException
} finally {
System.out.println(checkResult2); // false
}
}
}