2016-06-13 89 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

相关问题