■ Java Handling Exception(예외 처리)
• 오류 (Error)
- 메모리 부족 또는 프로그램 실행이 꼬이는 경우 등 프로그램 복구가 불가능한 상황
- 오류가 발생하는 원인을 찾아서 제거하는 방법으로 해결
• 예외 (Exception)
- 오류(Error)에 비해서 심각도가 낮고, 프로그램의 정상적인 흐름만 방해
- 파일을 읽으려 했으나, 해당 파일이 없는 경우
- 네트워크 연결이 유실되는 경우
- 문제 상황을 처리하는 로직을 구현하여, 런타임에서 자연스럽게 해결 가능
1. 예외 처리
- 예외가 발생했을 경우, 이 상황을 감지하고 처리하는 코드
- Throwable 클래스를 상속하는 자식 클래스로 이러한 문제들을 해결
• try ~ catch 문 종류
1. try ~ catch
try{
// 예외 발생 가능 코드
}catch(예외 클래스 e){
// 예외에 대한 처리 코드
}
2. multiple catch
- 다형성에 의해서 결정
- catch 하고 있는 클래스의 자식 클래스 예외가 발생해도 catch 가능
try{
...
}catch(ArithmetricException e){
...
}catch(Exception e){
...
}
3. try ~ catch ~ finally
- finally는 catch 발생 여부와 무관하게 실행
- try에서 생성한 리소스를 회수하기 위해 사용
try{
FileInputStream file = new FileInputStream("a.txt");
file.read();
}catch(IOException e){
System.out.println("파일 처리 실패");
}finally{
try{
file.close();
} catch (IOException e){
System.out.println("FileInputStream Close Fail");
}
}
4. try ~ catch ~ resource
- Resource를 종료할 필요가 있는 경우 사용
- AutoClosable 인터페이스를 구현하는 리소스를 자동으로 Close 처리
- AutoClosable의 close 함수 재정의. 즉, 해당 클래스의 close 함수를 자동적으로 호출.
try(FileInpuStream file = new FileInputStream("a.txt")){
file.read();
} catch(IOException e) {
System.out.println("File Read Fail")
}
2. 예외 종류 2가지
- 예외가 발생했을 경우, 이 상황을 감지하고 처리하는 코드
- Throwable 클래스를 상속하는 자식 클래스로 이러한 문제들을 해결
• Checked Exception
- Exception 클래스를 상속하고 있으면, Checked Exception
- Compiler에서 예외 발생 -> try ~ catch를 작성하지 않으면, Build가 되지 않는다.
• Unchecked Exception
- RunntimeException 클래스를 상속하고 있으면, Unchecked Exception
- try ~ catch를 작성하지 않아도 Build/Rrun이 가능
- ex> ArrayIndexOutOfBoundsException, ArithmetrixException
3. 예외 처리 위임
- 예외를 바로 처리하는 것이 아닌, 다른 곳으로 처리를 위임할 수 있다.
- throws 키워드 사용
• Checked Exception인 경우, 예외처리가 필요하므로 throws를 통해 위임
class CheckedExceptionThrow {
void methodA() throws IOException {
FileInputStream file1 = new FileInputStream("a.txt");
file1.read();
file1.close();
}
void methodB() {
try {
methodA();
} catch (Exception e) {
System.out.println("methodA 실패");
}
}
}
• Unchecked Exception인 경우, throws 키워드를 사용하지 않아도 자동으로 위임
class UnCheckedExceptionThrows {
void methodA() {
int x = 10 / 0;
}
void methodB() { // methodA()에서 throws가 없어도 자동적으로 위임된다.
methodA();
}
public static void main(String[] args) {
try {
new UnCheckedExceptionThrows().methodB();
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
}
}
• Method가 Overriding이 되는 경우
- 부모 클래스의 메소드를 Overrding 할 때는 부모 클래스의 메소드 예외보다 더 조상인 예외는 던질 수 없다.
- Overriding 할 때 구현하는 내용을 어느 정도 제한하고 있는 부분
class Foo {
void methodA() throws IOException {
FileInputStream file = new FileInputStream("a.txt");
} // Checked Exception
void methodB() throws ArithmeticException {
try {
FileInputStream file = new FileInputStream("a.txt");
} catch (IOException e) {
throw new ArithmeticException("에러 발생");
}
}
}
class BarOne extends Foo {
void methodA() throws IOException {
} // IOException을 상속 받는다.
}
class BarTwo extends Foo {
void methodA() throws FileNotFoundException {
} // 더 자식 Exception은 possible
}
class BarThree extends Foo {
// void methodA() throws Exception {} // not possible
}
4. 예외 발생시키기
- throws 키워드 사용하여 예외를 발생시킬 수 있다.
void exceptMethod1() throws IOException{
if(false)
throw new FileNotFoundException("Error"); // possible
}
void exceptMethod2() throws FileNotFoundException{
if(false)
throw new IOException("Error"); // not possible, FileNotFoundException이 IOException의 자식 클래스이므로
}
5. 사용자 정의 예외 클래스 선언 (Custrom Exception)
- 필요에 따라 사용자가 정의한 클래스를 선언할 수 있다.
- Exception or RuntimeException을 상속받는다.
class MyException extends RuntimeException {
enum ErrorCode {
ERROR_A, ERROR_B;
}
private ErrorCode errorCode;
public MyException(ErrorCode errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
@Override
public String getLocalizedMessage() {
String message = getMessage();
...
return localizedMessage;
}
}
'Coding > Java' 카테고리의 다른 글
Java Lambda Expression(람다식) (0) | 2020.09.18 |
---|---|
Java Inner Class(내부 클래스) (0) | 2020.09.18 |
Java Generic(제네릭) (0) | 2020.09.17 |
Java Enumeration(열거형) (0) | 2020.09.17 |
Java Abstract Class & Interface (0) | 2020.09.17 |