逆光飛行的玉珮

导航

[Java] 例外處裡 try/catch & throws

 

public class CheckException {
    public static void main(String[] args) {
        
        File file = new File("xxxx");
        FileInputStream fis = new FileInputStream(file);

因為沒有檔案,會出現FileNotFoundException

 

解決方法如下

1. 設立例外處裡  try/catch

public class CheckException {
    public static void main(String[] args) {
        
        File file = new File("xxxx");
        try {
            FileInputStream fis = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

 

2.使用throws(可丟多個),將指定錯誤出現的時候,將程序往外丟回給呼叫者處裡(可多層外拋)

public static void main(String[] args) throws FileNotFoundException{

也可指定父類別(囊擴範圍較大)的exception,將多種錯誤一同處理。

public static void main(String[] args) throws IOException{

 

可於內部主動設計throw,分設多種Eexception發生時的狀況外丟或throws

File file2 = new File("CCCC");
  if (!file.exists()) {
      throw new FileNotFoundException("找不到檔案");
    //FileNotFoundException exception = new FileNotFoundException("找不到檔案");
    //throw exception

 

posted on 2019-01-29 10:05  逆光飛行的玉珮  阅读(121)  评论(0)    收藏  举报