Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid many try catch blocks in java

I'm very new to java and the idea of try catch blocks to handle exceptions.

This roughly what I'm ending up with, and there simply has to be a better way:

    try {
        JSONObject jsonObject = new JSONObject(jsonString);
        int aCount = jsonObject.getInt("acount");
        String devTok = jsonObject.getString("dt");
        String qURL = jsonObject.getString("qu");
        try {
            DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
            Key qKey = KeyFactory.createKey("qu", qURL);
            int dsACount = (Integer) datastore.get(qKey).getProperty(kLastKnownANumber);
            //..etc.. more try catch blocks needed
        } catch (EntityNotFoundException e) {
            e.printStackTrace();
        }
    } catch (com.google.appengine.repackaged.org.json.JSONException e) {
        e.printStackTrace();
    }

There are more try catch blocks embedded in the same way, so that at the end, there is just a lump of catch blocks. How else should exceptions be handled, Eclipse keeps asking my to either surround with a try catch block or "Add throws declaration".

Sometimes I want to catch certain exceptions, for example if it can't find an entity, I want to print something like "Entity not found", and if the JSON string can't be parsed into an object, I want to print something like "Can't parse JSON".

(I'm used to objective-c where the are delegate methods for failure, or the method returns null and you have passed a pointer to [a pointer to] an NSError object, which will have been "filled", Is there somewhere to learn about try-catch?)

like image 625
Jonathan. Avatar asked Jul 05 '11 22:07

Jonathan.


People also ask

How do I stop multiple try catch blocks?

To avoid writing multiple try catch async await in a function, a better option is to create a function to wrap each try catch. The first result of the promise returns an array where the first element is the data and the second element is an error. And if there's an error, then the data is null and the error is defined.

Can I have multiple try catch blocks in Java?

Yes, we can define one try block with multiple catch blocks in Java. Every try should and must be associated with at least one catch block.

How do you handle multiple exceptions in catch block in Java?

If a catch block handles multiple exceptions, you can separate them using a pipe (|) and in this case, exception parameter (ex) is final, so you can't change it. The byte code generated by this feature is smaller and reduce code redundancy.

What can I use instead of try catch in Java?

throws: The throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself. 5. finally: It is executed after the catch block.


2 Answers

If all you're doing is catching them and printing the stack trace regardless of the exception type, you can just wrap the code in one large try/catch block. To save many "catches", you can catch java.lang.Throwable which is the interface that all exceptions implement. If not, you can have a catch for every type of checked exception the code you're calling throws, and handle them specifically.

Eclipse keeps asking you to do so because Java code will not compile if the checked exceptions are not caught, or declared to be thrown by the caller.

+Adding this comment to the answer (Thanks, Paul Tomblin):

In production quality apps you'd be logging the trace, adding some logic where you're handling the exception in a right way, taking an alternate flow, and/or re-wrapping it in another exception and throwing it, etc. It all depends on the particular problem you're trying to solve.

like image 95
lobster1234 Avatar answered Sep 30 '22 08:09

lobster1234


The idea of exception handling is that you can handle errors at points in your program flow where you can deal with them meaningfully. Rather than checking every function's return value like in C, where most of the time you can't do anything sensible other than passing the error further up, you install a try/catch block at sensible points in your program:

Basically, whenever there is a point where you can react meaningfully to an error, then catch that error, and pass everything else on. That way, error handling is only invoked when there is a plausible recovery from the error.

For example, worst case if any error stops your program from executing meaningfully, then you might almost not catch anything at all and just let the OS handle the situation (well, perhaps one single try/catch to produce a friendly error message).

Example (in C++, sorry, I'm can't type Java blind):

int main()
{
  try {
    while (masterloop()) { }
  catch (...) {
    LOG("Fatal program error, terminating!"); // nothing else we can do!
  }
}

/* lots of program logic */

void process_image()
{
  try {
    Image im = load_image_from_disk();
    /* ... */
  }
  catch (const OutOfMemoryExc & e) {
    LOG("Not enough memory to process the image.");
    return;
  }
  catch (const DataErrorExc & e) {
    LOG("Could not read the image data.");
    return;
  }
  catch (...) {
    throw; // pass everything else along
  }
}

In this example, we may try to process an image and fail for some anticipable reasons (out of memory, or failure to read the image). In that case we just return without doing work and let the program continue gracefully. All other errors are propagated up to a higher point. Most importantly, we do not need to litter the actual image processing function with error checks and responses all the time, it suffices for any code there to throw one of our two good exceptions and not worry any further.

Moral: If you have try/catch blocks absolutely everywhere, you're doing it wrong.

like image 33
Kerrek SB Avatar answered Sep 30 '22 10:09

Kerrek SB