Exception Handling in Java With Examples

What is Java exception handling?

The mechanism to deal with any unforeseen situation/event during the execution of the program is known as Exception Handling. Before diving deep into technicalities, let us look into a real-life example. We start our travel via bus from point A to point F. While traveling we have stoppages as B, C, D, and E in between. We find that our bus broke down at stoppage C. This was an unpredicted situation, which is uncertain and may or may not happen.

This situation of the unforeseen problem is represented as an Exception in Java. An exception is a condition that arises in a code sequence at a run time resulting in abrupt completion of execution.

Now comes the question, what to do now? We cannot terminate our journey abruptly. We will arrange for an alternative bus/commute to reach point F on time. That is, we are handling the situation. So, dealing with an exception to provide an alternative route for successful completion of the program is known as exception handling.

Fundamentals of exception handling

Java exception handling is based on five keywords: try, catch, throw, throws, and finally. Program statements where there is a scope for exceptions are monitored within a try block.  If an exception occurs within the try block, the exception is thrown. You can catch this exception (using catch) and handle it accordingly. System-generated exceptions are implicitly thrown by the Java run-time system. For any user-defined exception, we define the condition for exception and explicitly throw an exception using the keyword throw. Any exception that is thrown out of a method must be specified using  throws. Any code that absolutely must be executed without failing after a try block is positioned inside the finally block.

All the keywords mentioned here are applicable to the object of the Exception class.

This is the basic form of an exception-handling block:

try{
//block of code where exception might occur
}
catch(Exception1 obj){
//Handling if Exception1 occurs inside try block
}
catch(Exception2 obj){
//Handling if Exception1 occurs inside try block
}
finally{
}

Types of Exception

The exception class is a child class of java.lang.Throwable. All the exception class which is pre-defined and the ones which we can create will be the child of the Exception class.

Hierarchy.png

We will look into three types of situations and their handlers respectively.

Checked Exception:

The exception which is checked right at the compile time is known as a checked exception. These exception classes are a direct child of the Throwable class but not the runtime exceptions. E.g SQLException, IOException.

Unchecked Exception:

The exception which is checked right at the run time is known as an unchecked exception. Such an Exception class inherits the RuntimeException class.  E.g ArrayIndexOutOfBoundsException, ArithmeticException.

Error:

Exceptions that cannot be caught under normal circumstances by the program. Exceptions as such are used by the Java run-time system to indicate errors having to do with the run-time environment itself. E.g Stack overflow.

Some Example

We have a class MyException, with the main method where we are attempting to divide a number by zero.

public class MyException{
public static void main(String args[]){
int num=56;
int den =0;
double  frac;
frac=num/den;
System.out.println("Fraction is "+frac);
System.out.println("I will not be printed");
}
}

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero
       at MyException.main(MyException.java:6)

When the Java run-time system detects the attempt to divide by zero in line number 6, it constructs a new exception object and then throws this exception. This causes the execution of MyException to stop. The thrown exception must be caught by an exception handler and dealt with immediately. Here, we haven’t supplied any handler, so the exception is taken care of by the default handler provided by the Java run-time system. Any exception that is not caught/handled by the program will ultimately be processed by the default handler. The default handler displays the details of the exception, prints a stack trace from the point at which the exception occurred, and finally terminates the program.

One should notice the details, which we obtain upon exception occurrence.class name, MyException; the method name, main; the filename, MyException.java; and the line number, 6, are all included in the simple stack trace. Exception type: ArithmeticException, which more specifically describes what type of error happened.

public class MyException{

public static void main(String args[]){
myFaultyMethod();
}

public static void myFaultyMethod(){
int num = 56;
int den = 0
double  frac;
frac=num/den;
System.out.println("Fraction is "+frac);
System.out.println("I will not be printed");
}
}

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero
       at MyException.myFaultyMethod(MyException.java:9)
       at MyException.main(MyException.java:3)

As we can see here, there is a complete call stack that is displayed. As you can see, the bottom of the stack is the main’s line 3, which is the call to myFaultyMethod(), which caused the exception at line 9. The call stack is quite useful for debugging and locating the error precisely. 

This was an overview of Java Exceptions. We will introduce you to try, catch block in the next lecture.