Hello everybody,
It’s Michael, and today’s Java lesson will be on try-catch statements and exception handling in Java.
In Java lingo, exceptions are errors that occur in the program, which can be caused by coding errors made by the programmer, errors caused by incorrect input (in programs that utilize user input), or other unforeseeable things. When errors occur, Java will generate an error message-the technical term for this is throwing an exception.
Now let’s demonstrate errors in action. Consider the following program:
public class TryCatch
{
public static void main (String [] args)
{
int [] numbers = {1, 1, 2, 3, 5, 8, 13, 21, 34};
System.out.println(numbers[11]);
}
}
And here’s the error message we get when we try to run this code:
run:
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 11
at JavaLesson12.TryCatch.main(TryCatch.java:17)
/Users/michaelorozco-fletcher/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
In this example, we get an ArrayIndexOutOfBoundsException when we try to run the code. This is just one of the many types of exceptions you might run into.
We get this particular exception because we are trying to retrieve an array index that doesn’t exist. Since there are only 9 elements in this array, the highest index we can use is 8.
Now, let’s fix this program using a try-catch statement:
public class TryCatch
{
public static void main (String [] args)
{
try
{
int [] numbers = {1, 1, 2, 3, 5, 8, 13, 21, 34};
System.out.println(numbers[11]);
}catch (Exception e)
{
System.out.println(“Index out of bounds!”);
}
}
}
And here’s the output:
run:
Index out of bounds!
BUILD SUCCESSFUL (total time: 0 seconds)
So what exactly does the try-catch statement do? This statement (or rather statement pair) tries to catch an error (or exception) and, should an error be found, executes the block of code in the catch statement. In this case, an error is found, so the code in the catch statement is executed (the only thing that happens here is that Index out of bounds! is printed).
- Never have a
trystatement without a correspondingcatchstatement! - The
catchstatement will always haveException eas a parameter (though I’m not sure why).
You can also use the word finally after a try-catch statement. All this does is execute code after a try-catch statement is finished running (regardless of whether or not an error is found). Here’s an example:
public class TryCatch
{
public static void main (String [] args)
{
try
{
int [] numbers = {1, 1, 2, 3, 5, 8, 13, 21, 34};
System.out.println(numbers[11]);
}catch (Exception e)
{
System.out.println(“Index out of bounds!”);
}finally
{
System.out.println(“All done here”);
}
}
}
And here’s the output:
run:
Index out of bounds!
All done here
BUILD SUCCESSFUL (total time: 1 second)
There are basically no changes in the way the program runs-an error is found, so Index out of bounds! is printed. The only difference between this program and the one in the previous example is that the message All done here is printed after the try-catch statement is finished running. This happens because All done here is the block of code that corresponds to the finally statement.
Finallystatements will ALWAYS go after try-catch statements!
The last thing I wanted to discuss in this post is the throw statement. In Java, throw works similar to try-catch statements, except it allows you to create a custom error. Throw is always used with a Java exception type.
Here’s a sample program with throw (it’s not the same one from the previous examples):
import java.util.Scanner;
public class TryCatch
{
public static void main (String [] args)
{
Scanner sc = new Scanner (System.in);
int a, b, quotient;System.out.println(“Please pick a number: “);
a = sc.nextInt();System.out.println(“Pick another number: “);
b = sc.nextInt();quotient = a/b;
if (b == 0)
{
throw new ArithmeticException (“Can’t divide by 0”);
}else
{
System.out.println(“The quotient is: ” + quotient);
}
}
}
And here’s the output with b as 0:
run:
Please pick a number:
11
Pick another number:
0
Exception in thread “main” java.lang.ArithmeticException: / by zero
at JavaLesson12.TryCatch.main(TryCatch.java:27)
/Users/michaelorozco-fletcher/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 6 seconds)
Here’s the output with b not being 0:
run:
Please pick a number:
15
Pick another number:
5
The quotient is: 3
BUILD SUCCESSFUL (total time: 3 seconds)
In this program, I have a Scanner object and three int variables-a, b, and quotient (which equals a/b). After I set up the Scanner object, I ask the user to pick two numbers-the first number will be equal to a and the second number to b. I then divide a by b and store the result in the quotient variable.
An ArithmeticException will be thrown if b equals 0, since you can’t divide anything by 0. In the first example, I set b to 0 and my program threw an ArithmeticException. However in my second example, I set b to 3 and instead got the message The quotient is: 3.
Throwstatements are often used with custom methods, but those aren’t always necessary (after all, I didn’t use a custom method in this example). For more on custom methods, please read my previous post Java Lesson 11: Method Making.- There are at least a good 150 exception types in Java, so there’s no need to memorize them all. Here’s a handy guide to the various exception types in Java. Click on an exception type to learn more about it.
Thanks for reading,
Michael
