-1

我已经开始研究 Java 中的异常,但我不明白为什么这段代码的输出是:

Throw SimpleException from f()
Cought it!

代码是这样的:

    类 SimpleException 扩展异常 {}

    公共类继承异常{
        公共 void f() 抛出 SimpleException{
            System.out.println("从 f() 抛出 SimpleException");
            抛出新的 SimpleException();

        }

        公共静态无效主要(字符串[]参数){
            继承异常 sed = new InheritingExceptions();
            尝试 {
                sed.f();
            } 捕捉(SimpleException e){
                System.out.println("捡到了!");
            }
        }
    }
4

3 回答 3

1

您的代码正在做的是:

1) 创建一个名为 sed 的新 InheritingExceptions 对象

2) 你用 try-catch 块包装 sed.f() 方法。catch 块正在捕获 try{} 中抛出的任何 SimpleException

3) sed 调用方法 f() 。f() 正在执行以下操作:

  • System.out.println("从 f() 抛出 SimpleException"); -- 这将打印到控制台“Throw SimpleException from f()”
  • 抛出新的 SimpleException();

4) 由于 f() 方法抛出了 SimpleException,因此您的 try-catch 块会捕获它。当被抓住时,它会打印到控制台“Cought it!”

class SimpleException extends Exception {}

public class InheritingExceptions {
    public void f() throws SimpleException{
        System.out.println("Throw SimpleException from f()");
        throw new SimpleException();

    }

    public static void main(String[] args) {
        InheritingExceptions sed = new InheritingExceptions();
        try {
            sed.f();
        } catch (SimpleException e) {
            System.out.println("Cought it!");
        }
    }
}
于 2018-12-18T22:27:18.043 回答
0

因为在main()方法中你已经创建了一个 InheritingExceptions 类的对象,并且使用这个对象你正在调用f()InheritingExceptions 类的方法。

就像f()打印“从 f() 抛出 SimpleException ”一样,所以你的第一个输出行就是这个。也f()抛出 SimpleException() ,当f()main()您使用的方法调用时try-catch block,此块将捕获方法抛出的异常,f()并且 catch 块内的代码将被执行此执行将打印您的第二条语句“ Cought it!!”

于 2018-12-18T20:44:17.130 回答
0

看,当您在 main 中执行此操作时:

sed.f();

您正在调用该函数,并且在该函数 f() 中,您正在打印“从 f() 抛出 SimpleException”并抛出异常。在 main 中,您正在捕获该异常并打印“Cought it!”

于 2018-12-18T20:34:45.300 回答