Keep current with the latest trends in technical communication by subscribing to the I'd Rather Be Writing newsletter. 4,500+ subscribers

Recent Comments

Search results

Java: Handling exceptions

Quick summary

Try-catch blocks are ways of safeguarding your code from blowing up if there are errors.

Java runs the code in the try block; if there’s a problem, it runs the code in the catch block and keeps going through the routine. without catch blocks, the entire program would stop if it encountered an error. The catch block handles the error so your program can continue despite errors.

finally is a catch block that runs regardless of the error

Use catch blocks specific to the type of error you anticipate. There are 50+ type of errors that can be thrown.

Using catch blocks focused on a specific error will help you identify problems with the code

Run your more generic catch blocks last; this way your more specific catch blocks will identify the error more accurately.

Detailed description

Error handling is one of the most important concepts to consider in your code because it helps identify errors that are happening. When you set up your method, if you add a throws to your method, it will launch a specific type of error if that code fails. The code will stop running at that point and be handled by that type of exception.

Here I’ve identified that the run method will throw a FileNotFoundException.

publicvoidrun()throwsFileNotFoundException{Filefile=newFile("test2.txt");FileReaderfr=newFileReader(file);System.out.println("This won't run due to the error, because it wasn't enclosed in a try-catch block.");}

Now when I define the method this way, then I need to add the try catch block that handles this exception. This is a very important piece of information because it’s a way of letting the user know that if the code fails, it will throw those particular types of exceptions.

You can also list multiple types of exceptions that a method throws:

publicvoidrun()throwsFileNotFoundException,IOException{Filefile=newFile("test2.txt");FileReaderfr=newFileReader(file);System.out.println("This won't run due to the error, because it wasn't enclosed in a try-catch block.");}

But if you surround the code with a try-catch block, then the error will be handled through the catch block, and the code will keep running after that block. In other words, Java tries to run the code in the try statement. If an error occurs, Java goes to the catch block and runs that.

run(){Filefile=newFile("test2.txt");try{FileReaderfr=newFileReader(file);System.out.println("This won't be run if an exception is found.");}catch(Exceptione){e.printStackTrace();}System.out.println("This code still runs because it's outside the Try block.");}

In Eclipse, just surround the code you want to enclose with the try-catch block and right-click, then select **Surround with > Try Catch **block.

Although you can only have one try statement per try-catch block, you can have multiple catch blocks. This is useful if you want to handle different types of errors in different ways.

You can also add a finally block that will be processed regardless of whether an error takes place.

There’s also a try-multicatch block that you can add. You add this in the same way, by selecting the statement, right-clicking, and choosing Surround with > Multicatch.

Exception is the most generic type of exception. It will catch any type of exception, and therefore it must appear last, since you want to use specific error catches to better identify the type of error that is taking place.

try{// run some code here}catch(ParseExceptione){// handle the ParseException here}catch(Exceptione){// handle other exceptions}

If you look at this Exception page in the Javadoc, you can see that there are probably 50 different types of exceptions. You want to be really specific about the types of exceptions you catch so that you can more appropriately identify what might be wrong with your code.

You have to handle the exceptions in the right order. If you put the wrong exception first, it might catch the error before a more specific catch block handles the error.

The exceptions are automated when you use your IDE to add the try-catch blocks. The IDE will populate the exceptions based on the methods you’re using.

Finally

There’s also a finally keyword that you can leverage. Here’s an example:

try{averageImpl.setInts(ints2);}catch(IllegalArgumentExceptioniae){System.out.println("Oops! can't use an empty array");}catch(ArithmeticExceptionae){throwae;}finally{System.out.println("Made it past the exception!");}

– Java 7 for Absolute Beginners

What does finally do here?

The finally keyword lets you create a block of code that gets run no matter what. Even if an exception happens, the code in the finally block gets run.

Java 7 for Absolute Beginners

The logic of looking for exceptions

In Beginning Java 8 Fundamentals, the author explains an important concept about why Java uses try-catch blocks. Without them, your code would look like a bunch of nested if-else blocks:

// Connect to the databaseif(connectedtothedatabasesuccessfully){// Fetch the employee recordif(employeerecordfetched){// Update the employee salaryif(updateissuccessful){// Commit the changesif(commitwassuccessful){// Employee salary was saved successfully}else{// An error. Save failed}}else{//An error. Salary could not be updated}}else{// An error. Employee record does not exist}}else{// An error. Could not connect to the database}

I think PHP often looks like this. With them, however, your code is much cleaner: