为什么我不能使用'outer'catch来捕获嵌套catch子句中抛出的异常?

Laz*_*don 0 java nested exception try-catch

在下面的示例中,您可以看到无法使用外部catch子句捕获IOException(名为FOURTH)异常.这是为什么?我知道如果使用外部catch将其抛出到嵌套的try块中,则可以捕获异常.如果将b静态变量值更改为false,则可以看到这一点.

但是为什么我们不能使用外部catch来捕获嵌套catch子句中抛出的异常?

import java.io.*;

public class Exceptions {

    static boolean b = true;

    public static void main(String[] args){
        try {
            exceptions(b);
        } catch (Exception e) {
            System.out.println(e  + " is handled by main().");
        }       
    }

    static void exceptions(boolean b) throws Exception{
        try{
            if(b) throw new FileNotFoundException("FIRST");
            try{
                throw new IOException("SECOND");
            }
            catch(FileNotFoundException e){
                System.out.println("This will never been printed out.");
            }
        }
        catch(FileNotFoundException e){
            System.out.println(e + " is handled by exceptions().");
            try{
                throw new FileNotFoundException("THIRD");        
            }
            catch(FileNotFoundException fe){            
                System.out.println(fe + " is handled by exceptions() - nested.");
            }
            try{
                throw new IOException("FOURTH");
            }
            finally{}
        }
        catch(Exception e){
            System.out.println(e + " is handled by exceptions().");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

b = true时的输出:

java.io.FileNotFoundException:FIRST由exceptions()处理.java.io.FileNotFoundException:THIRD由exceptions()处理 - 嵌套.java.io.IOException:FOURTH由main()处理.

b = false时的输出:

java.io.IOException:SECOND由exceptions()处理.

Pet*_*rey 6

但是为什么我们不能使用外部catch来捕获嵌套catch子句中抛出的异常?

您可以.问题是你的最后一个catch(Exception e)处于相同的嵌套级别,这就是为什么它不会捕获先前catch块中抛出的异常的原因.

尝试嵌套这样的try/catch块

static void exceptions(boolean b) {
    try {
        try {
            if (b) throw new FileNotFoundException("FIRST");
            try {
                throw new IOException("SECOND");
            } catch (FileNotFoundException e) {
                System.out.println("This will never been printed out.");
            }
        } catch (FileNotFoundException e) {
            System.out.println(e + " is handled by exceptions().");
            try {
                throw new FileNotFoundException("THIRD");
            } catch (FileNotFoundException fe) {
                System.out.println(fe + " is handled by exceptions() - nested.");
            }
            // will be caught by the nested try/catch at the end.
            throw new IOException("FOURTH");
        }
    } catch (Exception e) {
        System.out.println(e + " is handled by exceptions().");
    }
}
Run Code Online (Sandbox Code Playgroud)