简体   繁体   English

在Java中一次捕获多个异常?

[英]catch multiple exceptions at once in java?

import java.io.*;

class West1 extends Exception {
    private String msg;
    public West1() {
    }

    public West1(String msg) {
        super(msg);
        this.msg=msg;
    }

    public West1(Throwable cause) {
        super(cause);
    }

    public West1(String msg,Throwable cause) {
        super(msg,cause);
        this.msg=msg;
    }


    public String toString() {
        return msg;
    }


    public String getMessage() {
        return msg;
    }
}

public class West {
    public static void main(String[] args) {
        try {
            throw new West1("Custom Exception.....");
        }catch(West1 ce) {
            System.out.println(ce.getMessage());
            //throw new NumberFormatException();
            throw new FileNotFoundException();
        }catch(FileNotFoundException fne) {
            fne.printStackTrace();  
        }/*catch(NumberFormatException nfe) {
            nfe.printStackTrace();
        }*/
    }
}

In the above code, NumberFormatException is thrown from catch block it compile and run successfully but when FileNotFoundException is thrown from catch block it will not compile. 在上面的代码中, NumberFormatException是从catch块抛出的,它已编译并成功运行,但是当FileNotFoundException从catch块抛出时,则不会编译。 Following Errors are thrown: 引发以下错误:

West.java:40: error: exception FileNotFoundException is never thrown in body of
corresponding try statement
                }catch(FileNotFoundException fne){
West.java:39: error: unreported exception FileNotFoundException; must be caught
or declared to be thrown
                        throw new FileNotFoundException();

So my question is what is reason behind this behaviour? 所以我的问题是这种行为背后的原因是什么?

NumberFormatException is a RuntimeException, meaning that it's not required to be declared in all methods it may be thrown. NumberFormatException是RuntimeException,这意味着不需要在可能引发的所有方法中都声明它。 This means that, unlike FileNotFoundException, the compiler can not know if it can get thrown in a block or not. 这意味着,与FileNotFoundException不同,编译器无法知道是否可以将其抛出一个块。

The title implies you are trying to catch multiple exceptions at once, and your code implies you understand that you can have multiple catch blocks for a single try block to catch different types of exceptions. 标题表示您试图同时catch多个异常,而代码则意味着您了解可以为单个try块拥有多个catch块,以catch不同类型的异常。 Everything is good so far, but you seem to misunderstand exactly where the try - catch catches errors. 到目前为止,一切都很好,但是您似乎误会了try - catch捕获错误的确切位置。

Here is you code. 这是您的代码。 I removed the comments to make it more concise. 我删除了评论以使其更简洁。

public class West {
    public static void main(String[] args) {
        try {
            throw new West1("Custom Exception.....");
        } catch(West1 ce) {
            System.out.println(ce.getMessage());
            throw new FileNotFoundException(); // <-- Must be caught
        } catch(FileNotFoundException fne) { // <-- Never thrown
            fne.printStackTrace();  
        }
    }
}

The first compiler error is because the catch block that is for catching FileNotFoundException 's try block never throws FileNotFoundException . 第一个编译器错误是因为用于捕获FileNotFoundExceptiontry块的catch块从不抛出FileNotFoundException The second compiler error is because FileNotFoundException is a checked exception . 第二个编译器错误是因为FileNotFoundException是已检查的异常 Because it is a checked exception your code must either 因为这是一个检查异常,所以您的代码必须

  • handle it (by catching it with try - catch ) 处理它(通过try - catch捕获它)
  • let everyone know it could throw it ( public static void main(String[] args) throws FileNotFoundException { ... ). 让每个人都知道它可能会抛出它( public static void main(String[] args) throws FileNotFoundException { ... )。

From the context of your code, you seem to be going with the first option, handling it with try - catch , but you have the catch in the wrong place. 从代码的上下文来看,您似乎选择了第一个选项,并使用try - catch处理,但是将catch放置在错误的位置。

catch blocks don't catch exceptions, try blocks do. catch块不捕获异常, try块可以捕获。 catch blocks specify what to do with the actual caught exception. catch块指定如何处理实际捕获的异常。

public class West {
    public static void main(String[] args) {
        try {
            throw new West1("Custom Exception.....");
        } catch(West1 ce) {
            System.out.println(ce.getMessage());
            try {
                throw new FileNotFoundException();
            } catch(FileNotFoundException fne) {
                fne.printStackTrace();
            }
        }
    }
}

Try that instead. 试试吧。 Notice how you can have a try instead of a catch . 注意如何try而不是catch This wouldn't matter if FileNotFoundException wasn't a checked exception . 如果FileNotFoundException不是检查的异常没关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM