正确抛出自己的异常(不要终止你的程序)

时间:2016-06-13 19:29:25

标签: java exception

我在抛出自己的异常时遇到了一些问题。这是代码:

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

1 个答案:

答案 0 :(得分: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();
        }

    }
}