Why I m getting Unreported Exception

纵饮孤独 提交于 2019-12-20 07:58:10

问题


can you please why error comes in line 13 as unreported exception ,must be caught pr declared to be thrown

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
    }
}

回答1:


You need to add a throws to the method that throws exceptions as mentioned before as well as all the methods that call that method




回答2:


At the last line of your code you are throwing an exception but there is nothing handling it. You must do one of two:

  1. Surround it with a try/catch block
  2. Use the throws keyword in the method's signature. See this SO question: The throws keyword for exceptions in Java

In addition this question: Why is “throws Exception” necessary when calling a function?


Secondly after adding it the code will compile but when executed will still throw an exception:

Exception in thread "main" java.lang.ArithmeticException: / by zero

Reason is that in the catch blocks you are re-throwing the exception.



来源:https://stackoverflow.com/questions/44861810/why-i-m-getting-unreported-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!