Reputation: 439
I am trying to figure out what is the best way to handle exceptions in java. Is it a good idea to throw RunTimeException inside a catch block or it is useless?
public final void clickOnElement(MobileElement mobileElement, int secondsToWait) {
try {
abstractPlatform.clickOnElement(mobileElement,secondsToWait);
} catch (Exception e) {
throw new NoSuchElementException("Wasn't able to click on element " + mobileElement);
}
}
Upvotes: 1
Views: 1444
Reputation:
It may or may not be useless, totally depends on how we use it. I have used it in a way so that I can maintain logs for exceptions.
public final void clickOnElement(MobileElement mobileElement, int secondsToWait)
{
try
{
abstractPlatform.clickOnElement(mobileElement,secondsToWait);
}
catch (Exception e)
{
logError(this, "clickOnElement()", "Wasn't able to click on element"+mobileElement);
throw new NoSuchElementException("Wasn't able to click on element " + mobileElement);
}
}
Now in this case I have created a method that logged exception for that particular method and by looking at the logs I might be able to figure out the cause of exception. But lets assume that this piece of code is being used in an API.
And as a API designer I want to return some specific status code instead of showing exception message send by the tomcat/framework. In that case we can throw the exception in catch and that exception can be held in some parent method or by the framework itself if there is some mechanism in place for that.
So its all upto how we use it.
Upvotes: 0
Reputation: 4607
No its not useless, I do this a lot in code I write I would rather see my own custom exception with a message about the error, since you are handling where it is caught in most of those cases you will know why it has thrown, so I much prefer to see an exception with a detailed message about the exact issue instead of a generic exception been thrown and just seeing an error message in the console, an example of something useless would be
try {
abstractPlatform.clickOnElement(mobileElement,secondsToWait);
} catch (Exception e) {
throw e;
}
Upvotes: 0
Reputation: 109613
Sometimes one indeed wants a RuntimeException instead of a checked exception.
} catch (Exception e) {
throw new NoSuchElementException("Wasn't able to click on element " + mobileElement, e);
}
I would specify the exact exceptions, like IOException|SQLException
, and add it as cause to the rethrow.
A recent use-case are lambdas that are in a context (streams) where checked exceptions are not allowed.
Or simply to add additional info that might help pinpoint the error, like file name or SQL statement & parameters.
Especially IllegalArgumentException and IllegalStateException can be more informative than other exceptions.
Upvotes: 3