Reputation: 91193
I have your standard try/catch
statement:
try
{
// Do a bunch of stuff
}
catch ( Exception e )
{
throw e;
}
Is there any way to determine what possible Exceptions could be caught from my code without trying to force my code to fail in order to see what type of Exception e
is?
For example, if I did some HTTP calls or maybe some JSON stuff that I want to handle differently, my code might look like this:
try
{
// Do a bunch of stuff
}
catch ( HttpException e )
{
// Do something
throw e;
}
catch ( JSONException e )
{
// Do something else
throw e;
}
catch ( Exception e )
{
throw e;
}
But maybe I'm doing a whole bunch of stuff in my code and I'm not sure (due to lack of Java experience) what the possible Exceptions are that could be caught...
Is there any possible way to use Eclipse to look at a set of code and get a list of every possible type of exception that could be caught?
Upvotes: 1
Views: 2623
Reputation: 62769
There is no way to get a list of possible unchecked exceptions. Since they are not declared anywhere (they are created on the fly) it's just not possible without a pretty specific code analyzer tool--and even then it might not catch some from compiled library classes.
For examples of tricky things to predict consider anything that allocates memory can throw an out of memory exception and you could even instantiate an exception reflectively which would be pretty much impossible to find with ANY static analysis tools.
If you are really really paranoid you could catch RuntimeException, that should get all unchecked exceptions that you would want to deal with--it's not a recommended tactic but can prevent your program from failing from some unknown/unseen future bug...
It's good form to put any thrown exceptions into comments but this practice is not consistently followed.
Upvotes: 1
Reputation: 405
In NetBeans, and probably Eclipse, if you simply enter the code without any try-catch block, the IDE will hint to you what exceptions will be thrown and offer to wrap the statements in a try-catch block. That's probably your easiest way to catch all the possible Exceptions.
Upvotes: 0
Reputation: 82579
Well there's two types of exceptions: checked and unchecked.
You can't get a list of all unchecked exceptions, because they might not tell you what they are. (They might, if you read the documentation for the libraries you're using.)
For checked exceptions, you wouldn't be able to compile the code if you weren't catching them all. I would simply remove the Exception e
block and compile with it. Honestly catching every exception is a bad idea unless you're truly prepared to handle it.
Upvotes: 3