繁体   English   中英

Java捕获不同的异常

[英]Java catch different exceptions

public class ExceptionHandler {

    public static void main(String[] args) throws FileNotFoundException, IOException {
    // write your code here
        try {
            testException(-5);
            testException(11);
        } catch (FileNotFoundException e){
            System.out.println("No File Found");
        } catch (IOException e){
            System.out.println("IO Error occurred");
        } finally { //The finally block always executes when the try block exits.
            System.out.println("Releasing resources");
            testException(15);
        }
    }

    public static void testException(int i) throws FileNotFoundException, IOException {
        if (i < 0) {
            FileNotFoundException myException = new FileNotFoundException();
            throw myException;
        }
        else if (i > 10) {
            throw new IOException();
        }
    }
}

此代码的输出给出

No File Found Releasing resources

java是否可以同时捕获IOException和FileNotFoundException? 它似乎只能捕获第一个异常,而不能捕获IOException

try块在引发的第一个异常处停止,因此永远不会执行第二次调用testException()

您应该将try/catch/finally块包含在另一个try/catch块中,因为您的finally块会抛出必须捕获的异常。

这是您的代码的工作方式:

  • testException(-5)抛出FileNotFoundException
  • FileNotFoundExceptioncatch (FileNotFoundException e)
  • No File Found被打印到标准输出中
  • 然后, finally执行块(不执行testException(10)语句)。
  • 这样就可以打印出Releasing resources
  • 然后执行testException(15)并抛出一个IOException ,但该IOException始终无法捕获(程序将被中断)。

如果从main方法中删除throws FileNotFoundException, IOException ,则编译器将警告您未捕获异常( finally块中的异常)。

暂无
暂无

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

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