본문 바로가기

Contact 日本語 English

【Java】 8강. Exception

 

8강. Exception 

 

추천글 : 【Java】 Java 목차 


1. Exception class [본문]

2. Exception handling [본문]

3. Exception generation [본문]


a. GitHub 


 

1. Exception class [목차]

 

Figure. 1. Exception class hierarchy

 

Throwable class = Error class + Exception class

⑵ Checked Exception 

① compilation time에서부터 확인되는 Exception. handle하지 않으면 compile error가 일어남

② 예시 

○ IOException 

○ ClassNotFoundException 

○ InstantiationException 

○ SQLException 

⑶ Unchecked Exception 

① RuntimeException의 subclass 

② JVM의 operation 동안에만 catch 할 수 있음. handle하지 않아도 compile error가 일어나지 않음

③ 예시

ClassCastException 

 NullPointerException

○ ArithmeticException 

○ IllegalArgumentException

○ IndexOutOfBoundsException 

⑷ Error class 

 handle할 수 없는 오류들. 심각한 수준

② 예시 

 StackOverflowError

 VirtualMachineError 

 OutOfMemoryError 

 

 

2. Exception handling [목차]

방법 1. actively handle exception 

① 문법 : try → catch → finally 순으로 실행됨

 

try { Action }    // statements that may cause an exception 
catch(ExceptionType parameter)    // error handling code
  { Handler }
finally { }    // statements to be executed

 

try 

○ Exception이 발생하면 나머지 코드는 execute되지 않고 즉각 catch로 이동

○ 상황에 따라 서로 다른 Exceptionthrow 할 수도 있음

catch

○ multiple exception : single bar |로 구분함

○ 예 : catch(FileNotFoundException|IOException e) 

유형 1. leave message for debugging : getMessage(), toString(), printStackTrace()

유형 2. resolve the error in an appropriate way, if possible 

④ finally 

 

String finleName = "/dev/null/NonExistentPath";
Scanner file = null;
try {
  file = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
  e.printStachTrace();
} finally { // Prevent Resource Leaks
  if(file != null){
    file.close();
  }
}

 

○ 주로 file이나 network connection을 종료하여 resource leak을 예방하는데 사용됨 

방법 2. (explicit) defer handling : 메소드에서 Exceptionthrows하여 caller로 하여금 handling하도록 하는 것

finally 앞에서 method가 종료돼도 finally 구문은 실행됨

 

static void pubfirstline(String fname) throws Exception {
  BufferedReader in;
  try {
    in = new BufferedReader(new FileReader(fname));
  } catch (FileNotFoundException e) {
    System.err.println("Could not open " + fname);
    throw e;
  } catch (Exception e){
    throw e;
  }
}

 

RuntimeException이 발생해도 굳이 caller가 handling하지 않아도 됨

○ JVM이 대신 handle하기 때문

○ main 함수도 explicit하게 Exceptionthrows할 수 있음

③ throws로 선언된 method에 catch문이 없어도 됨 : 이 경우 finally문은 있어야 함

⑶ try-with-resource statement

 

static String readLine(String path) throws IOException{
  try (BufferedReader br =
       new BufferedReader(new FileReader(path))) {
        return br.readLine();
  } // BufferedReader implements AutoCloseable 
}

 

① 자동으로 파일을 종료시켜주는 프로그래밍 기법

finally를 추가할 수도 있음

 

 

3. Exception generation [목차]

Exception class 정의 

 

class MyRuntimeException extends RuntimeException {
  public MyRuntimeException ( ) { }
  public MyRuntimeException(String message) {
    super(message);
  }
}

 

⑵ throw : Exception을 생성하겠다는 의미

⑶ throws : method에서 Exception을 defer 하겠다는 의미

① checked Exception의 경우 반드시 명시적으로 써야 함

RuntimeException의 경우 반드시 써야 하는 것은 아님

③ method 내에서 throw를 해주었으면 method name 옆에 throws Exception과 같이 써 주어야 함

④ method 옆에 throws를 썼어도 반드시 throw를 해야 하는 것은 아님

⑷ Exception in constructor 

① constructor name 옆에 throws Exception과 같이 표시

○ 별도로 throw new Exception();와 같이 하지 않으면 Exception을 throw하지 않음

② superclass 생성자에서 checked exception을 throws하면 subclass constructor에서도 그 checked exception을 throws

○ superclass에서 throw 해주었으면 subclass에서 별도로 throw new Exception();와 같이 하지 않아도 throw를 함

③ child method는 parent method와 동일한 타입의 exception을 throw

 

입력: 2020.11.02 21:48

'▶ 자연과학 > ▷ Java' 카테고리의 다른 글

【Java】 10강. design patterns  (0) 2020.11.17
【Java】 9강. 기타 문법  (0) 2020.11.04
【Java】 7강. File I/O  (0) 2020.10.28
【Java】 6강. 자료구조  (0) 2020.10.20
【Java】 Java 목차  (0) 2020.09.23