Java Exception Handling

Run time errors are those that happen while the program is executing. The reason might be you are dividing by zero or opening a file which is not present in system or some other unforeseen scenario. These type of errors occur at run-time, hence, it not possible to check for every condition to error safely. Even though we write code to safeguard all conditions, it may still lead to other unforeseen errors. To avoid these problems Java provides an efficient way of handling these errors, called Exception Handling.

Java defines different classes for the different types of exceptions. All these classes are derived from the base class Throwable. When an exception occurs in a program, Java creates an object of type Throwable and sends it to our program. By studying this object we can perform safety operations.

There are two direct subclasses of Throwable: Exception and Error.

In general exceptions of type Error are related to JVM, so we do not handle these exceptions. But the exceptions that are of type Exception class are related to our own program operations such as divide-by-zero or file not found etc. We need to handle these exceptions. The important subclass of Exception is RuntimeException, which is used to handle common issues that occur at run-time.

By using five keywords we can handle all exceptions in Java, they are: try, catch, throw, throws and finally. These are all interrelated and have their own purpose in handling exceptions. We will look at these keywords one by one.

try and catch

The try and catch keywords form the basis of complete exception handling in Java. The set of statements or code you want to monitor should be present in the try block, which should be followed by catch block with a specific exception type. Below is the simple syntax of try catch blocks.

try {
    // code to monitor for errors
}
catch (ExceptionType exOb) {
    // handle ExceptionType here
}

In the above syntax, ExceptionType is the class of the object we are expecting the statements present in the try block to throw. When the program is executing statements under the try block, it checks for any run-time errors. If any error occurred in try block then Java creates an object of that type and passes control to catch block by skipping any statements below the problematic statement. If no error occurs then it completely skips catch block.

In this below program, we have created an integer array of size 6 and we are initializing this array using for loop. We know that if we pass index value which is greater than or equal to the size of the array, the program crashes as we are accessing a memory location which does not exist. We place this assignment inside  a try block. As array index is the problem here, we wrote catch block with the exception of type ArrayIndexOutOfBoundsException. Here intentionally we iterated the for loop to go beyond the size of the array. When i becomes equal to the size of the array, program control jumps to catch block and skips println statement. The catch block will be executed.

/*
This is a simple Java program about Exception Handling.
Call this file KH_trycatchSample.java.
*/

class KH_trycatchSample {
	public static void main(String args[]) {
		int numbers[] = new int[6];				
		try {
			for (int i = 0; i <= 6; i++){ // equal is the cause of error
				numbers[i] = i+1;
				System.out.println("Value at index " + i + " is " + numbers[i]);
			}
		}
		catch(ArrayIndexOutOfBoundsException ex){
			System.out.println("Caught Index out of bounds exception");
		}
		System.out.println("End of try catch block");
	}
}

Download the code  Run the code

Output

Value at index 0 is 1
Value at index 1 is 2
Value at index 2 is 3
Value at index 3 is 4
Value at index 4 is 5
Value at index 5 is 6
Caught Index out of bounds exception
End of try catch block
<<< Java Interface References and Extending InterfacesMultiple catch blocks and nested try blocks >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .