Is there any specific protocol for handling exceptions in public methods? Consider this eg.
public int someMethod()
{
try{
code that might throw an exception
}
catch(Exception e)
{
log the exception
}
}
Say that this method might throw an ArrayIndexOutOfBoundsException. So, is it correct to handle this Exception in the method itself (as in the example) or throw it and assume that the calling method will handle the Exception?
Edit:
Further extending my question.
Consider the following function.
public int[] someMethod2()
{
try{
code that might throw an exception
}
catch(Exception e) {
log the exception
return new int[0];
}
}
As in the example code above, if I return an array of size 0, then the calling method will fail with an AraryIndexOutOfBounds Exception. If I return null, then the calling method will fail with NullPointer Exception. Since, I can modify the calling method, which way is better? Should I let the calling method fail? Or should I directly call System.exit() in someMethod2()?
Is there a tutorial which explains these decisions? This does not give me an answer.
Generally, don’t handle the exception if it doesn’t make sense to handle it yourself.
ArrayIndexOutOfBoundsExceptionusually is a sign of a programming error, and if your app contains programming errors, crashing is the correct and responsible thing to do.One big no-no is returning null instead of throwing exceptions, like this code:
Now, if you get
nullfrom this method, you don’t know why. Was the ID invalid? Is the database server down? Or was it some programming error in thequeryDatabasemethod?Edit: Oh, and you should never log and rethrow, it’ll just fill up your logs and make them unreadable. If you rethrow an exception, odds are that whatever code catches it further up the call chain will log it, too