Recommended Books

Java Exception Handling



This article covers the use of Exception Handling in Java.

In Java, all exceptions are represented by classes. All exception classes are derived from a class called Throwable. When an exception occurs in a program, an object of one of these exception classes is generated. There are two direct subclasses of Throwable, Exception and Error. Exceptions of type Error are related to errors that occur in the Java Virtual Machine itself, and not in your program. These types of exceptions are beyond your control, and your program will not usually deal with them.Thus, these types of exceptions are not described here.

Errors that result from program activity are represented by subclasses of Exception. For example, dividebyzero, array out of boundary, and file errors fall into this category. In general, your program should be able to handle exceptions of these types. These are the kinds of errors we’ll be discussing here.


General Syntax

Below is the general form for the try and catch keywords in exception handling. The use of both these keywords is compulsory, as they both go hand in hand. There are other optional keywords such as finally and throw related to exception handling that we will discuss further in this article.

try {
   // Coding that will potentially throw an error
}
catch (Exception1 obj) {
  // Code to be executed if Exception1 is thrown
}
catch (Exception2 obj) {
  // Code to be executed if Exception2 is thrown
}
.
.
.

The dots in the above code represent the fact that there may be any number of catch statements included in the code. Each catch statement is designed for a specific Exception, known here as Exception1 and Exception2. Whenever an exception is thrown, it’s value is passed into obj.

Remember that only a maximum of one catch code block may trigger. It’s not possible for multiple catch code blocks to trigger in the same run. It’s also possible that no catch block will trigger.


Example 1

Below is one of the simplest examples of exception handling in Java. The below code will produce a zero division error which shall be caught by the catch statement.

public class example {
	public static void main(String[] args) {
		int x = 5;
		int y;
		
		try {
			y = x / 0;
		}
		catch (ArithmeticException obj) {
                        System.out.println(obj);
			System.out.println("Zero Division Error occurred");
		}
                System.out.println("Handling Successful");
	}
}

The obj automatically receives the value of the exception and printing it out will usually make it clear what the error was, but we may choose to print out our own error messages like we did above.

java.lang.ArithmeticException: / by zero
Zero Division Error occurred
Handling Successful

The reason we included the “Handling Successful” print out was to show that due to our successful exception handling the program continued further than the try catch statement.

One thing to keep in mind, it is entirely possible for another exception to arise from within a catch statement’s code block. So be wary while writing code for the catch statement. Also know that it is possible to nest try catch statements, so you may have a try catch within another try catch statement.


Example 2

In this example we’ll be discussing the concepts of subclasses and superclasses. We mentioned earlier that all exceptions are part of a larger class called Throwable. Instead of using each subclass individually in our catch statements, we can use just the Throwable class. This helps us avoid a situation where we have to individually create catch statements for each possible exception (There are many). The obvious dis-benefit is that we don’t get to create unique scenarios for each exception.

In the example below we’ll be doing a hybrid of both ideas to get the best out of them. The order in which the catch statement are placed is important. If there are multiple catch statements, and one catch statement triggers, any catch statements after it will not be read as the try catch code will terminate.

public class example {
	public static void main(String[] args) {
		int x = 5;
		int y;
		
		try {
			y = x / 0;
		}
		catch (ArithmeticException obj) {
			System.out.println(obj);
			System.out.println("Zero Division Error");
		}
		catch (Throwable obj) {
			System.out.println(obj);
			System.out.println("Error detected");
		}
	}
}

As you can see, the catch statement for the Throwable class was not triggered. If any other exception has been thrown besides the Arithmetic Error, the catch statement with Throwable would have run instead.

java.lang.ArithmeticException: / by zero
Zero Division Error occurred

If you intend to use both subclasses and a superclass, make sure to keep the superclass below the subclasses. This allows the code to go through the other subclasses first.


Finally keyword

The finally block will be executed whenever execution leaves a try catch block, no matter what exceptions were thrown. You can think of it as something that will always run once the try catch block is over, regardless of the outcome. We’ll be using the previous example to illustrate this effect.

public class example {
	public static void main(String[] args) {

		try {
			throw new ArithmeticException();
		}
		catch (ArithmeticException obj) {
			System.out.println(obj);
			System.out.println("Zero Division Error occurred");
		}
		finally {
			System.out.println("All done");
		}
	}
}
java.lang.ArithmeticException
Zero Division Error occured
All done


Raising Exceptions

There may come a time where you want to raise exceptions manually. Perhaps something in your program wasn’t going the way you wanted, but since it technically doesn’t count as an error, nothing happens. This is where you can insert a throw keyword to manually raise an exception of your choosing.

public class example {
	public static void main(String[] args) {

		try {
			throw new ArithmeticException();
		}
		catch (ArithmeticException obj) {
			System.out.println(obj);
			System.out.println("Zero Division Error occurred");
		}
	}
}

As you can see, we deliberately threw an exception, and to prevent the program from crashing we used exception handling.

java.lang.ArithmeticException
Zero Division Error occurred

This marks the end of the Java Exception Handling article. Any suggestions or contributions for CodersLegacy are more than welcome. You can ask any relevant questions in the comments section below

Leave a Reply

Your email address will not be published. Required fields are marked *