How do you decide whether to add an exception to the method signature or handle it in the method?

I have quite a lot of experience with Java (math, UI, and graphics mostly), but I have never seriously worked with APIs like JDBC or org.w3c.dom

where you relied heavily on runtime checked exception handling. So if I write a bunch of methods that care about these APIs, how can I decide what to do with the exceptions, should I catch them right away, or add them to the method signature and thus throw the exceptions to a higher level of the frame stack where everything are they processed? It seems that all I would like to do with these checked exceptions is to exit the application with an error whenever it is encountered.

+3


source to share


5 answers


Typically, exceptions fall into two buckets: 1) the type that you can recover from in some meaningful way. 2) a type indicating a failure and possibly a need to report it (logging, returning an error page, displaying a dialog, etc.).

The first one you work with is close to where the exception occurs (for example, retry the http REST call), the last one you prefer to handle in one place instead of cluttering your code with catch blocks.

Web application validation exceptions are a good example of the kind you don't handle and instead you let the web application catch them and then map them against a 400 status response code.



Another example: Java will throw a checked exception for pretty much anything that accepts a character encoding. Usually you just want to go to "utf-8" and if you don't go wrong this exception will never happen. If that happens, then UTF-8 appears to be no longer supported. I don't see how you could recover from this in a meaningful way. I tend to catch and return them as unchecked exceptions. They will never happen, but when they do, I want the software to fail with an exception, so that it registers somewhere.

So, if any of the code you are using throws a thrown exception, you need to decide if you can restore it locally. If not, you need to decide if someone from the call stack needs / needs to know or handle the exception. If so, add it to your throws and push the solution onto the call stack. If not, roll it up as a thrown exception and handle it somewhere centrally (for example, write it down).

+3


source


The correct place to handle exceptions depends entirely on your specific situation. If you just want to exit the application, don't catch exceptions, but declare them in a throws clause.



However, for a server program, this would not be a good strategy. For example, you don't want your server to crash when the DB is unavailable due to a short network problem.

+2


source


This question is a little difficult to answer.

Let's say you go to the market to buy something, but you don't have cash in your valet. You have an ATM card from a bank, but again, you are not sure if you have enough money in your account to make purchases.

Now you can do two things. Or,

1) First you make sure you have enough money in your account before going to market, OR

2) Go to the market and then see if you can buy any items.

Likewise, there are two types of exceptions in java

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 considered synonymous with the first case when you are about to shop. Here, upon finding that you do not have enough balance to make purchases, you can decide to take it from someone or do nothing, that is, exit the purchase plan for the time being.

Likewise, Unchecked Exception can be thought of as you go to market without knowing about the balance in your account. Now on the account counter, your transaction will be successful OR it will be rejected because you do not have enough balance in your account. Here, too, you can decide to just apologize to the store clerk and leave, or you can call someone to bring the necessary money to the store.

As you can see, what you can do in these situations is entirely up to you.

Likewise, when programming with Java, there isn't much of a difference between Fixed and Unchecked Exception and what you want to do if Exceptions happened is entirely up to your personal / organizational policies.

The Java compiler only enforces this if, in the case of a method that threw Checked Exception, your code using that method must catch the Exception OR throw it up one level. Although in the case of Unchecked Exceptions, this is optional.

Take the following method as an example, 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 a BadUrlException or it can declare it as a throw, in which case the code using the storeDataFromUrl () method will have to do the same. That is, either catch the exception or throw it for someone above to deal with it the way they would like.

And now the same example that 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;
}

      

SEVERAL POINTS . Most books advise you to use checked exceptions for all errors from which the application can be recovered, and unrecoverable exceptions for errors from which the application cannot recover.

In reality, most applications will have to recover almost all exceptions, including NullPointerException, IllegalArgumentExceptions, and many other unchecked exceptions. The action / transaction could not be completed, but the application should stay alive and ready to perform the next action / transaction. The only time it is usually legal to close an application is during startup. For example, if there is no configuration file and the application cannot do anything reasonable without it, then it is legal to close the application.

The EDIT: . I can read these two articles to learn more about the topic: Three Rules for Effective Exception Handling and Best Practices for Exception Handling

+2


source


Well this is a tricky question. One of the five criteria of modularity from the book by B. Meyer is "Protection". This criterion says that if an error occurs in a class or module, it should not propagate in a hole system. Thus, the error must be isolated from another component of the system.

So I think you should catch the low level exception on the system.

+1


source


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

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

+1


source







All Articles