为什么我得到未报告的异常

时间:2017-07-01 14:05:24

标签: java exception-handling

请问为什么错误在第13行作为未报告的异常,必须被捕获pr声明被抛出

class Demo {
    public static void main(String args[]) {
        try {
            int x = 43 / 0;
        } catch (ArithmeticException ob) {
            throw ob;
        }

        try {
            int x = 43 / 0;
        } catch (Exception ob) {
            throw ob;
        }
        Exception ob = new Exception();
        throw ob;
        // Line 13 unreported exception Exception; must be caught or declared to be thrown
    }
}

2 个答案:

答案 0 :(得分:1)

在您的代码的最后一行,您抛出一个异常,但没有任何处理它。你必须做两件事之一:

  1. try/catch
  2. 围绕它
  3. 在方法签名中使用throws关键字。请参阅此问题:The throws keyword for exceptions in Java
  4. 另外这个问题:Why is “throws Exception” necessary when calling a function?

    其次在添加之后,代码将被编译但是在执行时仍然会抛出异常:

      

    线程中的异常" main" java.lang.ArithmeticException:/ by zero

    原因是在catch块中你重新抛出异常。

答案 1 :(得分:1)

您需要在前面提到的抛出异常的方法中添加throws以及调用该方法的所有方法