I'm doing a review for our codebase, and there are many statements like this:
try
{
doSomething()
} catch (Exception e)
{
}
but I would like a way to know which exception is thrown by doSomething() (there's no throw statement in the implementation of doSomething) so i can catch that exception instead of just catching Exception in general, even with findBugs it gives a warning REC_CATCH_EXCEPTION
.
I should mention that logging the exception or printing it to console will not help me because it takes time in this case to reproduce the error that causes the exception here.
Thanks
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:
doSomething
.doSomething
should be ready for.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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With