Show all functions that throw exceptions

二次信任 提交于 2019-12-12 21:04:28

问题


I am working on a Java program and I was wondering if there was some tool in Eclipse that would point out all of the methods that throw exceptions. I just want to make sure that I got all of them.

Thanks for the help,

Dan


回答1:


Checked exception must be caught so Eclipse will tell you about them. On the other hand unchecked exception (aka RuntimeException) are "not supposed to happen", it's most of the time a programming problem. Hence Java doesn't require to catch them and AFAIK Eclipse will not display any hints to tell you about a potential issue (it's probably better for visibility).

You can read Unchecked Exceptions — The Controversy, an article where Oracle gives its state of mind about unchecked exceptions.

If you want to build something yourself, look the Direct Known Subclasses of RuntimeException, it will help you to identify exceptions that can be thrown without being caught.




回答2:


First, search for the keywords. The 'throw' keyword will be in code that is detecting an error condition or can't handle some exception, while 'throws' will be methods declaring they pass on certain exceptions.

Eclipse may not be able to find all methods that throw exceptions because runtime exceptions do not need to be declared in 'throws' clauses, and may be thrown by a library call in which case you wan't find a 'throw' either.




回答3:


If you forget to catch a checked exception (extends Exception), the code will not compile. If you forget to catch a unchecked exception (extends RuntimeException), that's normally the better way. Read Up




回答4:


If your program catches Exception in the main method (initial execution context) you will be informed if some exception was throwed but not handled.

public static void main(String[] args) {
    try {
       // .... anything you want to do
    } catch(Exception e) {
       e.printStackTrace(); // useful to visualize the stack trace and ping point others places to catch exceptions
    } catch(Throwable t) {
       // if you want to check for errors also, but generally there isn't much to do in this case
    }
}

A side note, since Java implements the concept of checked (Exception) and unchecked RuntimeException) exceptions, is mandatory to deal with checked, and this informs the exceptions that a correct program should try/catch/finally. But unchecked informs situations normally indicating a bug, and good practices and defensive programming should avoid, so you don't have to deal with it.



来源:https://stackoverflow.com/questions/14822678/show-all-functions-that-throw-exceptions

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