How to know which exception is thrown

前端 未结 4 857
清歌不尽
清歌不尽 2021-02-03 11:29

I\'m doing a review for our codebase, and there are many statements like this:

try
{
   doSomething()
} catch (Exception e)
{

}

but I would l

相关标签:
4条回答
  • 2021-02-03 12:15

    Do you want to catch just compile-time exceptions or run-time exceptions as well? If you only want to catch the compile-time ones, just remove your current catch block - you'll immediately get error messages stating that certain exceptions aren't being caught. After you add one exception, you'll see error messages for others - you'll be able to finish catching all possible exceptions thrown by your code block.

    0 讨论(0)
  • 2021-02-03 12:19

    If there is no throws clause, then the method does not throw any checked execption. The javadoc of that method might give information about any unchecked exceptions the method can throw, but it does not have to.

    Why do you want to catch any exceptions in the first place?

    0 讨论(0)
  • 2021-02-03 12:22

    If there's no throws statement in doSomething (e.g. doSomething() throws IOException), any exceptions that will occur will be an instance of RuntimeException. If you want to know the exact class of an exception thrown by doSomething, you can always try

    try {
       doSomething();
    } catch (RuntimeException e){
       System.out.println(e.getClass().getName());
    }
    

    Knowing which runtime exceptions can be thrown without actually running the program is difficult. Even if none of the code that doSomething() calls has an explicit throw, core java operations can always throw NullPointerException, ArrayIndexOutOfBoundsException, etc with the wrong input. Here are some ideas:

    • Dig through manually. At least you will know some of the exceptions.
    • Use reflection to find any throw statements accessible from doSomething.
    • Run your test cases and log the exceptions thrown like above. Good tests will reveal the important errors that callers of doSomething should be ready for.
    • Go to the people who put the catch there in the first place

    In any case it's usually a good idea to catch exceptions that are as specific as possible, since you don't know exactly what went wrong when you try to deal with all cases in one clause.

    0 讨论(0)
  • 2021-02-03 12:30

    You can 1) dig through all the code in doSomething() and everything it calls to see the exception handling and what RuntimeExceptions can be thrown, or 2) take of the catch (Exception e) and wait for it to fail. This is the problem that checked exceptions attempted to overcome by making a strongly-typed declaration in method signatures about what exceptions must be handled as a result of calling the method.

    0 讨论(0)
提交回复
热议问题