2015年10月7日 星期三

Java 例外處理--AutoCloseable

有 catch 敘述:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class OpenFileDemo{
  public static void main(String[] args){
    System.out.println("About to open a file...");
    
    try (InputStream in = new FileInputStream("hello.txt")){
      System.out.println("File is opened..");
      int data = in.read();
    } catch (FileNotFoundException e){
        System.out.println(e.getMessage());
    } catch (IOException e){
        System.out.println(e.getMessage());
    }
  }
}

沒有 catch 敘述(利用 throws,丟給上頭去傷腦筋...)
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class ThrowDemo {
    public static void main(String[] args){
        try {    
            int data = readByteFromFile();
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }

    private static int readByteFromFile() throws FileNotFoundException, IOException {
        try(InputStream in = new FileInputStream("a.txt")){
            System.out.println("File is opening...");
            return in.read();
        }
    }
}