How to propagate exception from an overridden method in Java - java

What is the best practice to terminate the execution of an overridden method?
Here is the example code that explains the context:
#Override
protected String doInBackground(String... params) {
URL serverURL = null;
try {
serverURL = new URL((urlString));
} catch (MalformedURLException e) {
e.printStackTrace();
}
...
...
return response.toJSONString();
}
In the above code snippet, I am forced to catch MalformedURLException, so I used the try catch block. If that exception occurs, I would like to skip all the code below the catch block and propagate either the same exception or a different one that I would throw within the catch block until all the way to the Main method, hopping through the catch blocks and skipping the code in the middle in all the calling methods. How to do this?
The problems are:
1) I cannot add throws clause to the method signature because it is overridden and the base class doesn't allow it.
2) Since the method has to return a String, I have to specify the return statement after the catch block.(What do I return if an exception has occurred?)
3) Use System.exit in catch block - As some other posts on this forum point out, that may not be a good practice when you want your code to be reusable.

The best practice for such a case would be to wrap the MalformedURLException with a RuntimeException:
catch (MalformedURLException ex) {
throw new RuntimeException("Failed constructing URL", ex);
}
Ideally, you'd really like to edit the method's throws clause so it can accommodate any exceptions that are likely to stem from overrides; but since this is impossible in your case (as per your conditions), the above seems most reasonable to me.
A related best-practice would be to avoid logging the exception before wrapping it. From a design perspective, there's no need to do so — the caller already has access to the original Exception object (through the getCause() method of the thrown RuntimeException) so the caller should decide whether to log it or not.

Related

Java Exception handle case

public void backendExecute(Map appParams, BackendTaskMetaData metaData) throws Throwable {
try {
PeriodicTaskData ptd = (PeriodicTaskData) appParams.get(PeriodicTaskData.PARAM_KEY);
String bizKey = ptd.getBusinessKey();
} catch (Exception e) {
LogServices.app.error("RPTPeriodicReportGenTask:"+ e.getMessage());
}
}
With regards to the method above, if object pointed to is null, would come across as NullPointerException, I want to know if this exception would be caught or thrown to the invoker method? thanks
Exception is a parent class of NullPointerException, so it will catch it and not throw it to the calling method.
As you are catching Exception class and NullPointerException is its subclass , exception will get catched not throwed.
Regard to above method, if object ptd is null, would come across nullpointexception,
Yes.
i want to know this exception would be catch or throw it to invoker method?
The exception would be caught by the handler. The handler will catch Exception and any exception that is descended from it. NullPointerException is a subclass of RuntimeException which is (in turn) a subclass of Exception. Therefore, it will be caught.
Now, if this may be just an illustrative example ... but it is a bad idea to:
declare a method as throws Throwable, or
catch Exception ... unless you are about to terminate the application.
Declaring a method as throwing Throwable makes it next to impossible for the caller to know what exceptions could be thrown. Instead, the compiler will insist that the caller catches ... or propagates Throwable.
Catching Exception has the problem that you will catch every subtype of Exception ... including various unchecked exceptions that 1) you are not expecting, and 2) are probably symptoms of bugs that you cannot safely recover from.
NullPointerException is a subclass of Exception and thus will be catched, however it is recommended that you don't try and catch runtime exceptions. It is better to avoid them.
For example a null pointer could be avoided by doing the following:
if(ptd != null) {
ptd.getBusinessKey();
} else {
//Notify the user in some way or do something else.
}
catch (Exception e)
means that this will catch any exception (i.e. any subclass of Exception) thrown inside the preceding try block - which, yes, includes NullPointerException. Note that this is generally considered a bad practice, as you almost always will want to handle different sorts of exceptions in different ways, hence the need for multiple catch statements.
For instance, consider a method that could potentially throw an IllegalAccessException at compile time or a NullPointerException at runtime - it's difficult to imagine a situation where you'd want to handle them the same way, so you'll typically want to do something like this:
try {
PeriodicTaskData ptd = (PeriodicTaskData) appParams.get(PeriodicTaskData.PARAM_KEY);
String bizKey = ptd.getBusinessKey();
} catch (NullPointerException e) {
//do something
} catch (IllegalAccessException e) { //for example...
//do something different
}

Idiom to let a specific exception bypass a broad catch block?

Often, when implementing a template method or interface method, you can only throw one specific type of exception defined by the method. But your implementation may make class to API's that throw an incompatible exception type, or many different exception types.
Naturally you need to catch them and wrap the exceptions into the type suitable for the implemented method signature. Lets assume we want to implement this interface:
public interface SomeDataGetter {
public long getSomeData() throws IOException;
}
Our implementation makes use of some other API product to implement this, and the API method we are calling may have this signature:
public long loadFromDBOrCache(Object ... params) throws SQLException, IOException, ObjectNotFoundException, RuntimeException, FridayException, NotWeekendException, NumberIs42Exception;
I made this up to demonstrate the case where you can't exactly enumerate all the possibly thrown exceptions by concrete type. Do note that IOException is a type we are allowed to throw from our implementation.
Now I can go the lazy route when implementing this and wrap anything to fit my signature:
#Override
public long getSomeData() throws IOException {
try {
return loadFromDB(...);
} catch (Exception e) {
throw new IOException(e.getMessage(), e);
}
}
This will obviously wrap any exception into an IOException (even an IOException) and it works out ok. But I'd like to not wrap IOExceptions, since I am allowed to throw those without wrapping them:
#Override
public long getSomeData() throws IOException {
try {
return loadFromDB(...);
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOException(e.getMessage(), e);
}
}
You can imagine this gets cumbersome quickly if there are multiple possible exception in the implementation and multiple exceptions you are allowed from the implementation. I need an extra catch for each exception I want to pass throgh.
Whats the best idiom to keep that readable (also, I'm lazy, and don't want to write all these extra catches) and still avoid unneccessary exception nesting? Or shoud I not bother and just wrap everything?
One approach would be making a method that wraps all "prohibited" exceptions in an allowed one, while returning all the allowed ones unwrapped, like this:
private static void throwIoException(Exception e)
throws IOException // <<= Add other "allowed" exceptions here
{
if (e instanceof IOException) {
throw (IOException)e;
}
... // <<= Add checks for other "allowed" exceptions here
throw new IOException(e.getMessage(), e);
}
Now you can use a single catch block, and do the wrapping as needed:
try {
return loadFromDB(...);
} catch (Exception e) {
throwIoException(e);
}
One unpleasant consequence of this is that the stack trace shows the utility method at the top of the newly created IOException, but that's not important, because the real exception is the wrapped one, not the IOException wrapper. If the exception that you caught happens to be IOException, the correct stack trace should remain in place.
I would consider the lazy route of wrapping all exceptions you get into IOExceptions (or another checked exception) to be a bad practice. Instead I would consider wrapping the exceptions in runtime exceptions, thereby bypassing the catch or specify requirement. E.g.
#Override
public long getSomeData() throws IOException {
try {
return loadFromDB(...);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
The reason why this is better is that checked exceptions carry a certian meaning. If you catch for instance a ParseException in your code and rethrow that as a IOException you are lying. As a user of your code I might be able to do something about certain types of checked exceptions, but if you obfuscate the true cause of an exception it will be more difficult to debug the code when an error occurs.
In general I think you should minimize the use of checked exceptions since it litters error handling code throughout your application. Also if you are using someone else's code you have no guarantee that a RuntimeException won't be thrown anyway (unless you carefully read through it all). Therefore you have to consider that possibility anyway and handle it somewhere so your application don't crash. The virtues of unchecked exception vs checked exceptions has been discussed quite a lot elsewhere here and here for instance.

Declare method to throw an exception and subclass of this exception

Is it meaningful to declare a method to throw an exception
and a subclass of this exception,
e.g. IOException and FileNotFoundException?
I guess that it is used in order to handle both exceptions by a caller method differently.
However, is it possible to handle both exceptions if the method throws only the most generic i.e IOException?
However, is it possible to handle both exceptions if the method throws only the most generic i.e IOException?
Absolutely. You can still catch them separately:
try {
methodThrowingIOException();
} catch (FileNotFoundException e) {
doSomething();
} catch (IOException e) {
doSomethingElse();
}
So it makes no difference to what the caller can do if the method declares both - it's redundant. However, it can emphasize exceptions that you might want to consider. This could be done better in Javadoc than just the throws declaration.
Is it meaningful to declare a method to throw an exception and a subclass of this exception, e.g. IOException and FileNotFoundException?
Usually not - most IDEs I know of even issue warnings for such declarations. What you can and should do is to document the different exceptions thrown in Javadoc.
However, is it possible to handle both exceptions if the method throws only the most generic i.e IOException?
Yes it is, you just need to ensure that the catch blocks are in the right order, i.e. more specific first. Catch blocks are evaluated in the order they are defined, so here
try {
...
} catch (FileNotFoundException e) {
...
} catch (IOException e) {
...
}
if the exception thrown is a FileNotFoundException, it will be caught by the first catch block, otherwise it will fall to the second and dealt with as a general IOException. The opposite order would not work as catch (IOException e) would catch all IOExceptions including FileNotFoundException. (In fact, the latter would result in a compilation error IIRC.)
However, is it possible to handle both exceptions if the method throws only the most generic i.e >IOException?
catch(IOException ex){
if(ex instanceof FileNotFoundException){}
}
But this doesn't look clean, Throwing both exception looks good, even caller would come to know to that this method may throw these these exceptions, so they will handle it properly
Yes, it's possible to handle both if the method only throws IOException.
The best way to answer such a question is to write a test to demonstrate it and try it out. Let the JVM tell you the answer. It'll be faster than asking here.
yes. when certain specialized exceptions can be handled correct. It is, if you handle the exceptions as follow:
try {
} catch (FileNotFoundException f) {
//Try a different file
} catch (IOException ioe) {
//Fatal, Maybe bad blocks ... Bail out...
} catch (Exception e) {
//Something went wrong, see what it is...
}
Declaring, that the method may throw (more generic) IOException, and (more specific) FileNotFoundException is usually a good thing - it's an additional information for people using your code later. Note that you should explicitely state in the JavaDoc, under what circumstances is each of the exceptions thrown.
They will still be able to distinguish the exceptions, and handle them differently using catch constructs like this one:
try {
yourAwesomeMethod()
} catch (FileNotFoundException ex) {
// handle file-not-found error
} catch (IOException ex) {
// handle other IO errors
}

Rethrowing checked exceptions

public void foo() {
begin();
try {
...
commit();
} catch (Exception e) {
rollback();
throw e;
}
}
In the sample above, there is an error because foo has no throws Exception. Adding that wouldn't make do the method's usability a lot of good either.
What's the best way to do this? How do you do something if an error occurs without really "handling" the error?
Since Java 8 we use
/**
* Cast a CheckedException as an unchecked one.
*
* #param throwable to cast
* #param <T> the type of the Throwable
* #return this method will never return a Throwable instance, it will just throw it.
* #throws T the throwable as an unchecked throwable
*/
#SuppressWarnings("unchecked")
public static <T extends Throwable> RuntimeException rethrow(Throwable throwable) throws T {
throw (T) throwable; // rely on vacuous cast
}
You can rethrow a checked exception, but only by avoiding the compilers checked exception validation.
public void foo() throws MyCheckedException {
begin();
try {
...
commit();
} catch (Exception e) {
rollback();
// same as throwing an exception without the compiler knowing.
Thread.currentThread().stop(e);
}
}
Before you use stop() you should read http://download.oracle.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html
Thread.currentThread().stop(e) .. is behaviorally identical to Java's throw operation, but circumvents the compiler's attempts to guarantee that the calling method has declared all of the checked exceptions that it may throw:
At least two approaches come to mind, which are usually going to be combined depending on what you want foo to do:
1. Catch and rethrow only the relevant exceptions
There are only so many exceptions the code in your main flow can throw (probably mostly SqlExceptions). So only catch and rethrow those, and declare that you're doing so. More to the point, rethrow only the ones you're not actually handling (in your simplified sample code, you're not handling any, but your real life code is probably more subtle).
Mind you, some of the exceptions may be runtime exceptions, and so you may want to combine this with the below.
2. Don't catch the exception at all
Like this:
// Signature changes to include any exceptions that really can be thrown
public void foo() throws XYZException, ABCException {
// A flag indicating that the commit succeeded
boolean done = false;
begin();
try {
// Don't have any `return` statements in here (or if you do,
// set `done` to `true` first)
...
commit();
done = true; // Commit didn't throw an exception, we're done
} finally {
// finally clause always happens regardless
if (!done) {
// We must be processing an exception; rollback
try {
rollback();
} catch (Exception e) {
// quash it (e.g., leave this block empty), we don't want
// to mask the real exception by throwing a different one
}
}
}
}
Naturally your signature needs to include any exceptions that may be thrown in the main flow, but that's what you're trying to do, if I'm understanding you correctly.
Again, you may well combine these two approaches, because you may want to handle some exceptions and not others.
Wrap it with some RuntimeException which is unchecked.
Adding that wouldn't make do the method's usability a lot of good either.
No. It will be good at documentation, also caller will take care handling it.
Also See
exception-thrown-inside-catch-block-will-it-be-caught-again
throws-or-try-catch
I'd say that in this case rolling back is handling the exception appropriately. It's one of the few cases where it's legitimate to catch and re-throw.
Simply catching and logging an exception is not what I would consider handling. Rather than rethrowing, in that case I'd rather see checked exceptions added to the method signature and let it bubble up.
you may throw a subclass of RuntimeException - they don't require a catch()
the key point is, why should you throw a new Exception from a catch block.
if you use catch then handle your exception there in your catch. If you have to inform the caller method with an exception, then don't catch the exception with try-catch, instead, sign your method with throws and let the caller catch the e xception.
or throw a RuntimeException, i find this idea less useful because of lack of readability, then you don't need to sign your method with throws.
Here you've chanced on one of the biggest religious schisms in the Java, ( if not wider ) , world. It boils down to those that feel, as TJ seems to, and I do too, that checked exceptions are valuable for many reasons, VS the Rod Johnson/Spring school that in the design of Java, checked exceptions were used in many instances where they shouldn't, say closing a resultset or socket, so because it was wrongly used in many cases, it makes them useless so all exceptions should be unchecked. There are many classes in the Spring framework that are very thin wrappers around standard Java objects, but convert checked exceptions to unchecked. It drives me berserk!
Anyway, put me down as strongly agreeing with everything TJ has said, but know that you'll probably never find a "right" answer.
It's worth mentioning some advances in this area.
First, in Java 7, it's possible to catch and throw generic exceptions, as long as what's declared inside the try block is caught or declared in the outer block. So this would compile:
void test() throws SQLException {
try {
conn.commit();
} catch (Throwable t) {
// do something
throw t;
}
}
This is well explained here : http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html
Another way is described here : http://blog.jooq.org/2012/09/14/throw-checked-exceptions-like-runtime-exceptions-in-java/
The reason you may want to use that has often to do with lambdas, or throwing exceptions from some generic methods. I ran into this when I wanted to replace repeating constructs of:
try {
do_operation
flag_success
} catch (Throwable e) {
flag_error
throw e;
}
With using a method of:
public static void wrapExec(RunnableT s) {
try {
s.run();
flag_success
} catch (Throwable t) {
flag_error
doThrow(t);
}
}
and therefore replacing the whole try/catch block with just
wrapExec(()->{do_operation})

Handling Multiple Exceptions within a Method

I am currently working on the maintenance of a piece of code that is a little bit "Exception Happy." Basically, ever method or anything throws Exception. I'm going to work to take care of that, but, in the meantime, I am wondering what is the best way to handle individual exceptions within a smaller block of code, such as a method. Is it better to do something like this:
public void aMethod()
try {
//Lots of code in here. Many lines.
} catch(Exception e) {
// TODO - Handle All Exceptions, but fairly generically
}
}
Or something like this:
public void bMethod() {
try {
// One line of code.
} catch(Exception e) {
// TODO - Handle a specific Exception (may even involve rethrowing it with more information)
}
// More code.
try {
// Another line of code.
} catch(Exception e) {
// TODO - Handle another specific exception.
}
}
I realize this is a pretty basic question, but after looking at hundreds of methods with Exceptions coming out of every one, I'm starting to wonder how best to handle all of them and what a best practice may be here.
First off, you should only put code in try/catch blocks that is exception worthy. For instance, having an unexpected value is not necessarily an exception, but trying to read from a file that doesn't exist is.
To answer your main question, you should put the exceptionable code in the same try {} block and catch specific questions in order of granularity in multiple catch blocks after the main try.
//Regular code that doesn't need to be covered by a try/catch block
try {
//critical code only
} catch (NullPointerException npe) {
//Code
} catch (RandomException re) {
//code
} catch (Exception e) {
//code
}
The answer to your question is: it depends.
if the code in the try block is coherent where it makes no sense to proceed in the event of an error, the first approach is best
if the code is taking seperate steps that are relatively unrelated (parsing numbers for instance) and can be recovered without aborting the rest of the method the seconds appraoch makes sense
A general remark on the code you inherited; it sounds like exceptions are abused to pass state around, I would refactor so that exceptions are caught at the spot where they can be handled and introduce return values or attributes to handle the state.
your bMethod isn't very useful illustration. Try to reprase it. Anyway, you have two options:
catch exceptions and log them.
catch exceptions and throw new RuntimeException(ex) (rethrow a runtime exception, setting the original as a cause)
Also, you will need to differentiate between exceptions. If your system has many custom exceptions, they are probably defined for a reason, and specific behaviour is expected when one of them is thrown.
If the try/catch block isn't adding useful information, just allow the method to throw the exception and have it handled where the caller can sensibly do something with the exception. This could cut down the number of try/catch significantly (by an order of magnitude).
BTW a trick for rethrowing any exception is.
try {
// do something
} catch (Throwable t) {
Thread.currentThread().stop(t); // rethrow any exception.
}
In addition to the suggestions already made you may also want to consider extracting try/catch blocks from the "meat" of the function.
public void delete(Page page) {
try {
deletePageAndAllReferences(page);
}
catch (Exception e) {
logError(e);
}
}
private void deletePageAndAllReferences(Page page) throws Exception {
deletePage(page);
registry.deleteReference(page.name);
configKeys.deleteKey(page.name.makeKey());
}
private void logError(Exception e) {
logger.log(e.getMessage());
}
This lets you focus your attention on the function you are really interested in without the exception handling getting in your way.

Categories