본문 바로가기

Java

예외 선언(Exception Handling) - 메서드에 예외 선언하기, finally 블럭

- 예외를 처리하는 방법은 두 가지인데,

  하나는 try~catch문이고, 다른 하나는 예외 선언하기 입니다. 

 

1) 예외 선언하기

- 예외 선언하기는 다음과 같이 할 수 있습니다. 

void method() throws Exception1, Exception2, ... ExceptionN{
	// 메서드의 내용
}

void method() throws Exception{
    // 메서드의 내용
}

- 다음과 같이 Exception이 선언되어 있다면,

  method2에서 Exception을 throw하지만,

  method2, method1, main에 try~catch문이 없으므로, 

  main문이 죽으면서 예외를 JVM에 넘겨주고, 비정상 종료됩니다. 

  그러면 JVM의 기본 예외처리기가 예외문을 출력합니다.

  실제로는 try~catch문이 있어야 예외문이 처리됩니다.  

class Ex8_9{

    public static void main(String[] args){
        method1();
    }
    
    static void method1() throws Exception{
        method2();
    }
    
    static void method2() thrwos Exception{
        throw new Exception();
    }
}

// 실행 결과
Exception in thread "main" java.lang.Exception
	at Ex8_9.method2(Ex8_9.java:11)
    at Ex8_9.method1(Ex8_9.java:7)
    at Ex8_9.main(Ex8_9.java:3)

- 이 예제는 createFile에서 Exception을 throw하고 main 메소드에서 try~catch문으로 처리합니다. 

import java.io.*;

class Ex8_10{

    public static void main(String[] args){
       try{
         File f = createFile(args[0]);
         System.out.println(f.getName()+"파일이 성공적으로 생성되었습니다.");
       }catch(Exception e){
         System.out.println(e.getMessage()+ " 다시 입력해 주시기 바랍니다.");
       }
    }
    
    static File createFile(String fileName) throws Exception{
       if(fileName == null || fileName.equals("")){
         throw new Exception("파일 이름이 유효하지 않습니다.");
       }
       
       File f = new File(fileName);
       
       f.createNewFile();
       return f;
    }
}

- 반면 createFile에서 직접 try~catch문으로 예외를 처리할 수도 있습니다.

import java.io.*;

class Ex8_10{

    public static void main(String[] args){
         File f = createFile(args[0]);
         System.out.println(f.getName()+"파일이 성공적으로 생성되었습니다.");
    }
    
    static File createFile(String fileName) throws Exception{
       try{
           if(fileName == null || fileName.equals("")){
             throw new Exception("파일 이름이 유효하지 않습니다.");
           }
       }catch(Exception e){
          fileName = "제목없음.txt";
       }
       
       File f = new File(fileName);
       
       f.createNewFile();
       return f;
    }
}

 

2) finally 블럭

- 예외 발생 여부와 관계없이 수행되어야 하는 코드를 넣습니다. 

try{
  // 예외가 발생할 가능성이 있는 문장들을 넣는다.
} catch(Exception1 e1){
  // 예외처리를 위한 문장을 적는다.
} finally{
  // 예외의 발생 여부에 관계 없이 항상 수행되어야 하는 문장들을 넣는다.
  // finally 블럭은 try~catch문의 맨 마지막에 위치해야 한다. 
}

 

참고

남궁성 자바의 정석