Java: Error Handling
Zander Bailey
Posted on February 2, 2020
Errors happen. We might like to believe our code is unbreakable, or that we have accounted for every possible input. But when we send code out into the jungle where it can be run by wild users, someone, somewhere, will probably find a way to break it. So it is important to have your code ready not just for the possible, but for the improbable and the impossible. For this reason, it is important to implement error handling, so that when someone breaks the unbreakable, the program will have some recourse. Today we’re going to talk about error handling in Java, but many languages use a similar structure once you know what to look for. One of the main ways of error handling in Java is something called a Try-catch block, which is used to catch possible errors and deal with them appropriately. This consists of two parts, the Try section, where we attempt to run some code, and the Catch section which catches an exception and deals with it in a user-specified manner. There is also a possible third section, Finally, but we’ll deal with that later.
Let’s say you’re indexing into an array that might not have the index you expect, and in that case you want your program to act accordingly:
try {
char[] letters = {'a','b','c'};
next = letters[20];
}catch(Exception e){
System.out.println(e);
}
In this example, the array only has 3 entries, so trying to call the index 20 will trigger an ArrayIndexOutOfBoundsException. When that happens it will jump down to the catch
block and run that code instead. Usually it will be something like this, where you print the exception so we know what happened, or sometimes you might print a custom message so you know what part of the code it broke down in, although that can also be accomplished with a traceback. In this example I have used the generic class Exception for my catch block, which catches all types of exception, but you can get more specific with this part. IF you want to handle all exceptions the same, you can just use Exception, but if you want to handle some exceptions differently you can refer to specific types of exceptions. In this case, we could print a specific message if we get can ArrayIndexOutOfBoundsException, and a different message if we get anything else:
try {
char[] letters = {'a','b','c'};
next = letters[20];
}catch(ArrayIndexOutOfException e){
System.out.println("Bad Index! Number is too big!");
}catch(Exception e){
System.out.println(e);
Additionally, in Java 7+ you can look for more than one type of exception in one catch statement, like catch(ExceptionType1 e || ExceptionType2 e)
. Prior to Java 7 it is necessary to have multiple catch blocks even if they have the same behavior. There is also a third part you can use, called a Finally statement. Finally allows you to execute code regardless of whether or not the Try statement throws an exception:
try {
char[] letters = {'a','b','c'};
next = letters[20];
}catch(Exception e){
System.out.println(e);
}finally{
Sytem.out.println("Hi anyway!")
}
One other way to handle errors is to pass them back up to the parent function by using the thow
keyword. This gives you the option to create exceptions that might not otherwise be thrown by telling it when to throw exceptions:
public class MyClass {
static void checkAge(int age) {
if (age < 21) {
throw new ArithmeticException("You must be at least 21 years old to order alcohol.”);
}
else {
System.out.println("You are old enough!");
}
}
public static void main(String[] args) {
checkAge(19);
}
In this instance, we want to ensure that if the age is less than 21 we don’t serve the client alcohol, so we throw an exception. throw
is not to be confused with throws
, which is a keyword used with a method definition, and indicates that an exception might be thrown by that method in order for it to be handled by the parent method. There are many ways to handle exceptions, and you might find variations of some or all of these in other languages.
Posted on February 2, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024