
In Java, by using exception handling technique in java we handle runtime errors to maintain the normal flow of the program and we avoid abnormal termination. In exception handling we define some alternative way by which we make the program to maintain the normal flow of the program even if there is an exception in the program.
Before going into details about exception handling let us understand what is exception, is it possible to remove exception completely, can exception occur during compile time?
Exception is actually an exceptional event, in other words we can say that it is an unexpected event which we do not want during the execution of the program. It disrupts the normal flow of the program. The exception comes during program execution.
The most important thing about exception is that all exceptions happen only at run time but compiler checks some exceptions at compile time, and JVM checks some exceptions at run time.
Table of Contents
Exception Hierarchy
Throwable class is the root of the entire exception and it represents all errors and exceptions. In other words, we can say that Throwable class is the super class of all the exceptions in Java.
Thowable class has two child classes which are as follows:
- Exception
- Error
Exception
Exception is caused by our program which we write, we can handle it by writing program of exception handling.
Error
If this happens then we cannot do anything, that means we cannot handle the error. This is usually due to lack of resources.
Checked Exception Vs Unchecked Exception
Checked Exception: Exception which the compiler checks for smooth execution of the program.
Unchecked Exception: If JVM checks exception then we consider such exception as an unchecked exception.
You should know whether exception is “checked” type or “unchecked” type, but all exceptions are run time exceptions. Not likely to happen at compile time.
Fully Checked Vs Partially Checked
If all the child classes of a checked exception is checked type then we consider such exception as fully checked. For example, IOException.
If some of the child classes of the checked exception are unchecked then such type of exception we consider as partially checked. For example, Exception
In Java, the only two exceptions are partially checked exceptions which are Throwable and Exception.
try…catch in exception handling
By using try…catch block we handle the exception in java. Some code we write in try block and some code in catch block. Let’s see in details which code should we write in try and catch block.
try {
// Code which may throw an exception
}
//catch and finally blocks . . .
try {
// Code which may throw an exception
} catch (ExceptionType name) {
// Block of code to handle errors
}
Try with multiple catch in exception handling
The order of the exception is very important if you use multiple catch block. You should write from child to parent. If you follow parent to child approach then you may get exception like “Exception XXXXX has already been caught“.
try {
// Code which may throw an exception
} catch (ExceptionType name) {
// Block of code to handle errors
} catch (ExceptionType name) {
// Block of code to handle errors
}
Finally Block in exception handing
If you are using try…catch then sometime you may required to write the clean up code like setting null to object, closing the files and so on, in this case you should write the such code inside the finally block.
try {
// Code which may throw an exception
} catch (ExceptionType name) {
// Block of code to handle errors
} catch (ExceptionType name) {
// Block of code to handle errors
} finally {
// Block of clean-up code
}
Finally block is the most important part of exception handling. Statements in the finally block will execute first, regardless of whether the return statement exists inside a try or catch block.
try {
// Block of code // Place 1
return statement; // Place 2
} catch (ExceptionType name) {
// Block of code to handle errors
} catch (ExceptionType name) {
// Block of code to handle errors
} finally {
// Block of clean-up code // Place 3
}
Execution order: Place 1 Place 3 Place 2
If we use System.exit(0) , the only condition is that the program flow will not come to finally block because JVM goes into shutdown in this case.
throws clause in exception handling
By using throws clause we can pass the responsibility of exception handling to the caller method.
throw clause in exception handling
As a programmer during programming sometimes we need to create a new object of exception and we want JVM to handle the exception. For such purpose we use throw keyword.
By using throw keyword we explicitly hand over the object of exception to JVM. We can use throw keyword to throw user defined exceptions in Java. And in most of the cases we use throw keyword for user defined exception.
You can use this technique if you required to show to custom message for the exception.
throw new IOException("This is custom message");
Types of Exceptions
There are following types of exception available in java:
Built-in Exceptions
These are the exception which are already available in Java. Whenever particular events occurs, JVM automatically raises these exception. For example,
ArithmeticException ArrayIndexOutOfBoundsException ClassNotFoundException IOException
User-defined Exceptions
Sometimes we write a code to define our own exception which handles the exception as per our requirement. If the built-in exception is not able to describe a condition, we write a user-defined exception.
This program will show you how to do exception handling in Java using User Defined Exceptions.
class UserDefinedException extends Exception {
public UserDefinedException(String s) {
super(s);
}
}
public class UserDefinedExceptionDemo {
public static void main(String args[]) {
try {
throw new UserDefinedException("User Defined exception in GeekCer");
} catch (UserDefinedException ex) {
System.out.println("UserDefinedException Caught");
ex.printStackTrace();
}
}
}
To find the difference between final, finally and finalize click here.
References:
https://docs.oracle.com/javase/tutorial/essential/exceptions/