3

I have quite a lot of experience with java (math, UIs and graphics mostly), but I've never seriously worked with APIs like JDBC or org.w3c.dom where you are heavily relied on handling checked runtime exceptions. So if I write a bunch of methods woriking with those kind of APIs, how do I decide what should I do with exceptions, whether I should catch them right away or add them to method's signature and thus propatate exceptions to a higher level of the frame stack, where they all are handled? It seems that all I would ever want to do with those checked exceptions is to exit the application with an error whenever one is encountered.

gvlasov
  • 18,638
  • 21
  • 74
  • 110

5 Answers5

3

This question is a bit difficult to answer.

Lets say, you are going to the market to buy something, but you don't have cash in your valet. What you have is an ATM card of some bank, but again you are not sure of whether there is enough money in your account to do the shopping.

Now, there are two things you can do here. Either,

1) You first make sure that you do have sufficient money in your account before leaving to the Market, OR

2) Reach out to the market and then see, if you can buy any items.

Likewise, In java there are two types of Exceptions

Checked Exception which is a sub-class of java.lang.Exception, and 
Unchecked Exception which is a sub-class of java.lang.RuntimeException.

Checked Exceptions can be thought of synonymous to the first case of you going to shopping. Here after finding that you don't have enough balance to do the shopping, either you can decide to borrow it from someone OR do nothing, that is, quit the plan of shopping for now.

Similarly, Unchecked Exception can be thought of as you going to the market without knowing about the balance in your account. Now, at the billing counter either your transaction will be successful OR it will be declined because you don't have enough balance in your account. Here also, either you can decide to just apologize to the shop-keeper and get going OR you can call someone to bring the required money to the shop.

As you can see, what you may do in such situations is totally dependent on you.

Similarly, In programming with Java there is not much difference between the Checked and Unchecked Exception and what you want to do if Exceptions occurred is totally dependent on your personal/organizations policies.

The Java compiler only mandates this that in case of a method throwing Checked Exception, your code using that method must have to catch the Exception OR throw it one level up. While in case of Unchecked Exceptions, this is optional.

Take for Example the following method which throws a Checked Exception :

// Here compiler makes sure that you either catch exception OR declare it to be thrown
public void storeDataFromUrl(String url){
    try {
         String data = readDataFromUrl(url); 
    } catch (BadUrlException e) {
         e.printStackTrace();
    }
}

// Here BadUrlException is a subclass of Exception    
public String readDataFromUrl(String url) throws BadUrlException{
    if(isUrlBad(url)){
        throw new BadUrlException("Bad URL: " + url);
    }
    String data = null;
    //read lots of data over HTTP and return it as a String instance.
    return data;
}

Now your storDataFromUrl() method can either catch the BadUrlException OR it can declare it to b throw, in which case the code using the storeDataFromUrl() method will have to do the same thing. That is, either catch the exception or throw it for someone higher to deal with it as they would like.

And now the same example, which throws an Unchecked exception;

// Here compiler does not force you to either catch exception OR declare it to be thrown
public void storeDataFromUrl(String url){
         String data = readDataFromUrl(url); 
}

// Here BadUrlException is a subclass of RuntimeException    
public String readDataFromUrl(String url) { // Notice, it does not have a throws clause
    if(isUrlBad(url)){
        throw new BadUrlException("Bad URL: " + url);
    }
    String data = null;
    //read lots of data over HTTP and return it as a String instance.
    return data;
}

FEW POINTS Most of the Books advice you to use checked exceptions for all errors the application can recover from, and unchecked exceptions for the errors the application cannot recover from.

In reality most applications will have to recover from pretty much all exceptions including NullPointerException, IllegalArgumentExceptions and many other unchecked exceptions. The action / transaction that failed will be aborted but the application has to stay alive and be ready to serve the next action / transaction. The only time it is normally legal to shut down an application is during startup. For instance, if a configuration file is missing and the application cannot do anything sensible without it, then it is legal to shut down the application.

EDIT : Yo can read these two articles for more understanding on the topic : Three rules for effective exception handling and Best Practices for Exception Handling

Amitesh Rai
  • 866
  • 11
  • 21
3

Generally, exceptions fall into two buckets: 1) the type you can recover from in some meaningful way. 2) the type that indicates failure and possibly a need to communicate that (logging, return some error page, display a dialog, etc.).

The former you handle close to where the exception happens (e.g. retry an http REST call), the latter you preferably handle in one place instead of littering your code with catch blocks.

Validation related exceptions in web applications are a good example of the type that you don't handle and instead you let the web application trap them and then map them to a status 400 response code.

Another example: Java throws a checked exception on just about anything that takes a character encoding. Generally you just want to pass in "utf-8" and unless you mistype that, that exception will never happen. If it does happen, it means UTF-8 is apparently no longer supported. I don't see how you could recover from that in a meaningful way. I tend to catch and rethrow these as unchecked exceptions. They'll never happen but when they do, I want the software to fail with an exception so that it gets logged somewhere.

So, if some code you are using throws a checked exception, you need to decide if you can recover from it locally. If not, you need to decide if somebody up the call stack should want/need to know about or handle the exception. If so, add it to your throws and move the decision up the callstack. If not, rethrow it as an unchecked exception and handle it somewhere centrally (e.g. log it).

Jilles van Gurp
  • 7,927
  • 4
  • 38
  • 46
2

The right spot to handle exception depends entirely on the concrete situation. If you just want to exit the application don't catch the exceptions but declare them in the throws clause.

For a server program however, this would not be a good strategy. For example, you don't want your server to crash whenever the DB is not reachable because of a short network problem.

Henry
  • 42,982
  • 7
  • 68
  • 84
1

Well,this is a difficult question.One of the five modularity criteria from B.Meyer book is Protection.This criterion says that if an error apear in a class,or a module,it should not spread in the hole system.So the error must be isolated from the other component of the system.

Therefor I think you should catch the exception on a low level in the system.

Luci
  • 85
  • 1
  • 12
1

If exception indicates problem that is caused by external sources like problem with network, bad format of xml etc. (it depends on exception type). then you should catch such exception where you can do something about it - if thats GUI application, then catch it where you can show error dialog to user - and make him/her make decision. If thats on server, then log error - return it to client. If exception is due to programming bug, then on GUI application you can log it / or allow user to send it in email to user. For command line tool I would allow application to exit with exception and throw all its data to output, if thats GUI application - I would rather try to catch it and try to recover with giving hint to user that there is a problem.

You could also add global exception handler to your program that will automatically send such exceptions to your email.

marcinj
  • 48,511
  • 9
  • 79
  • 100