简体   繁体   中英

How to propagate exception from an overridden method in 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM