2016-06-13 93 views
-2

我有一些問題拋出我自己的異常。下面是代碼:正確地拋出你自己的異常(使它不終止你的程序)

class MyException extends Exception { 
    private String message; 

    public MyException(String message) { 
     this.message = message; 
    } 

    @Override 
    public String toString() { 
     return "Something went wrong: " + message; 
    } 
} 

代碼,其中MyException拋出:

static void expand(String input, String output) throws MyException { 
    try { 
     Scanner sc = new Scanner(new File(input)); 
     //do something with scanner 
    } catch (FileNotFoundException e) { 
     throw new MyException("File not found!"); 
    } 
} 

和主要方法:

public class Encode { 
    public static void main(String[] args) throws MyException { 
     expand("ifiififi.txt", "fjifjif.txt"); 
     System.out.println("ok"); 
    } 

異常通常拋出,該消息被正常打印,但該程序被終止並且「ok」消息不被打印出來。

Exception in thread "main" Something went wrong: File not found! 
at vaje3.Encode.expand(Encode.java:59) 
at vaje3.Encode.main(Encode.java:10) 
Java Result: 1 
+3

'擴展( 「ifiififi.txt」, 「fjifjif.txt」);'未包裹在'嘗試-catch'子句,所以錯誤冒泡至'main'和,因爲沒有捕獲它,終止程序 – Michael

+0

即使在主方法中聲明瞭異常,它仍然會退出。正如@Michael所說的那樣,由於擴展周圍沒有任何嘗試,所以沒有調用ok。 – lordoku

+0

Oookay,但是在主要的方法(超過展開方法)try/catch做什麼?你如何得到MyException消息? – Rok

回答

0

你正在努力嘗試拋出一個新的例外。你不需要這樣做,只需傳遞原文即可。這是更好的做法,因爲FileNotFoundException是一個標準錯誤,所以它是大多數程序員共享的約定。

public class Encode { 
    static void expand(String input, String output) 
    throws FileNotFoundException 
    { 
     Scanner sc = new Scanner(new File(input));//no try catch here or new exception 
                //just let the original be passed up 
                //via the throw directive 
     //Do more here. 
    } 


    public static void main(String[] args) { 
     try{ 
      expand("ifiififi.txt", "fjifjif.txt"); 
     } catch (FileNotFoundException fnfe){ 
      System.err.println("Warning File not found"); 
      fnfe.printStackTrace(); 
     } 

    } 
} 
+0

是的,我知道這樣做比使用它容易100倍,但是我們必須實現我們自己的例外功能。 – Rok

相關問題