Exception 객체 생성됨Exception 객체가 소멸되지 않으면 프로그램이 비정상적으로 종료됨Java Exception Inheritance Hierarchy 참고
ArithmeticExceptionNumberFormatExceptionInteger.parseInt()NullPointerExceptionnull일 때 객체에 접근ArrayIndexOutOfBoundsExceptionClassCastExceptioninstanceof를 이용해 형변환이 가능한지 확인하는 것이 필요함// 문법
try {
// ... Exception이 발생할 가능성이 있는 구문
} catch (ExceptionClassType Variable_Name) {
// ... Exception 발생 시 수행할 구문
} finally {
// Exception 발생 유무에 관계 없이 반드시 수행해야 하는 문장
}
tryException이 발생할 가능성이 있는 코드를 try로 감싸기try 블록 안에 있는 문장들은 Exception이 발생하지 않는 한 모두 정상 수행됨Exception이 발생하면 발생 즉시 Exception 객체를 catch 블록으로 전달catchException 객체를 받아서 예외 상황 발생 시 수행할 문장들을 작성함finallytry 블록 안 코드의 Exception 발생 유무와 상관 없이 반드시 수행해야 하는 문장catch 블록 모두 끝난 후 finally 블록 작성close 해주려고)// 문법
try {
// ... Exception 발생 가능성 있는 구문
} catch (ExceptionClassType_1 Variable_Name) {
// ... Exception 1 발생 시 수행할 구문
} catch (ExceptionClassType_2 Variable_Name) {
// ... Exception 2 발생 시 수행할 구문
}
try 블록 안 코드에서 여러 Exception 발생할 가능성 있을 땐 catch 블록을 여러 개 작성Exception 발생하면 위에서부터 차례대로 검사하면서 알맞은 catch 블록을 찾아 수행Exception부터 상위 클래스의 Exception 순서로 작성Exception 클래스를 작성하여 모든 예외사항 처리할 수 있음throwsException을 상위 메소드로 던짐// 문법
public Return_Type Method_Name (Param_1/*, ...*/) throws Exception_Type_1, Exception_Type_2/*, ...*/ {
// ... method implementation
}
try-catch 구문에서 catch를 여러 번 사용할 수 있듯이, throws도 여러 개의 Exception을 던질 수 있다.main method에서 throw하면 상위 메소드가 없기 때문에 Exception 발생 시 프로그램이 비정상 종료된다.Exception을 발생시켜 예외 상황을 만들 수 있다.// 문법
throw new Exception("Exception 발생 메시지");
throw Exception_Object;
////// 강제 발생 두 가지 예시
// 1
Exception exception = new Exception();
throw exception;
// 2
throw new Exception("예외 발생");
// 예제
try {
boolean isInvalid = false;
// ...
if(isInvalid) throw new Exception("예외 발생");
// ...
} catch (Exception e) {
System.out.println(e.getMessage());
}
catch 구문에서 상위 메소드로 넘겨준다?try {
// ...
} catch (Exception e) {
throw e;
}
Exception 클래스로는 프로그램의 다양한 논리적 예외를 표현할 수 없다.Checked Exception 또는 Unchecked Exception 두 가지 종류로 정의할 수 있다.Exception 클래스를 상속 받아 정의RuntimeException 클래스를 상속 받아 정의Exception으로 끝나는 것이 좋다.String 타입 매개변수 갖는 생성자String 타입 매개 변수에 예외 발생 원인을 알려주는 메시지를 담아 전달Class TimeInputException extends Exception {
public TimeInputException() {
// 기본 생성자
}
public TimeInputException(String message) {
super(message);
}
}
public static void main(String[] args) {
try {
int time = readTime();
System.out.println(time);
} catch (TimeInputException e) {
System.out.println(e.getMessage());
}
// main 메소드에서 Exception을 처리해 주지 않는다면,
// Exception이 main 메소드를 호출한 jvm에게까지 넘어가게 되고
// 프로그램이 비정상 종료된다.
}
public static int readTime() throws TimeInputException {
Scanner scanner = new Scanner(System.in);
int time = scanner.nextInt();
if(time < 0) {
TimeInputException e = new TimeInputException("시간이 음수로 입력되었습니다.");
throw e;
}
return time;
}