Exception handling is one of the most important feature of java programming that allows us to handle the runtime errors caused by exceptions.
An Exception is an unwanted event that interrupts the normal flow of the program. When an exception occurs program execution gets terminated. In such cases we get a system generated error message. The good thing about exceptions is that they can be handled in Java. By handling the exceptions we can provide a meaningful message to the user about the issue rather than a system generated message, which may not be understandable to a user.
There can be several reasons that can cause a program to throw exception. For example: Opening a non-existing file in your program, Network connection problem, bad input data provided by user etc.
If an exception occurs, which has not been handled by programmer then program execution gets terminated and a system generated error message is shown to the user. For example look at the system generated exception below:
An exception generated by the system is given below
Exception in thread "main" java.lang.ArithmeticException: / by zero at ExceptionDemo.main(ExceptionDemo.java:5)
ExceptionDemo : The class name
main : The method name
ExceptionDemo.java : The filename
java:5 : Line number
This message is not user friendly so a user will not be able to understand what went wrong. In order to let them know the reason in simple language, we handle exceptions. We handle such conditions and then prints a user friendly warning message to user, which lets them correct the error as most of the time exception occurs due to bad data provided by user.
Exception handling ensures that the flow of the program doesn’t break when an exception occurs. For example, if a program has bunch of statements and an exception occurs mid way after executing certain statements then the statements after the exception will not execute and the program will terminate abruptly. By handling we make sure that all the statements execute and the flow of program doesn’t break.
Errors indicate that something severe enough has gone wrong, the application should crash rather than try to handle the error.
Exceptions are events that occurs in the code. A programmer can handle such conditions and take necessary corrective actions. Few examples:
Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their own exceptions.
Exceptions can be categorized in two ways:
Built-in exceptions are the exceptions that are available in Java libraries.
Below is the list of important built-in exceptions in Java.
// Java program to demonstrate ArithmeticException
class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0");
}
}
}
//Java program to demonstrate NullPointerException
class NullPointer_Demo
{
public static void main(String args[])
{
try {
String a = null; //null value
System.out.println(a.charAt(0));
} catch(NullPointerException e) {
System.out.println("NullPointerException..");
}
}
}
// Java program to demonstrate StringIndexOutOfBoundsException
class StringIndexOutOfBound_Demo
{
public static void main(String args[])
{
try {
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
}
}
}
//Java program to demonstrate FileNotFoundException
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {
public static void main(String args[]) {
try {
// Following file does not exist
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
} catch (FileNotFoundException e) {
System.out.println("File does not exist");
}
}
}
// Java program to demonstrate NumberFormatException
class NumberFormat_Demo
{
public static void main(String args[])
{
try {
// "akki" is not a number
int num = Integer.parseInt ("akki") ;
System.out.println(num);
} catch(NumberFormatException e) {
System.out.println("Number format exception");
}
}
}
// Java program to demonstrate ArrayIndexOutOfBoundException
class ArrayIndexOutOfBound_Demo
{
public static void main(String args[])
{
try{
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("Array Index is Out Of Bounds");
}
}
}
// Java program to demonstrate IOException
class IOException_Demo {
public static void main(String[] args)
{
// Create a new scanner with the specified String
// Object
Scanner scan = new Scanner("Hello Geek!");
// Print the line
System.out.println("" + scan.nextLine());
// Check if there is an IO exception
System.out.println("Exception Output: "
+ scan.ioException());
scan.close();
}
}
// Java program to demonstrate NoSuchElementException
public class NoSuchElementException_Demo {
public static void main(String[] args)
{
Set exampleleSet = new HashSet();
Hashtable exampleTable = new Hashtable();
exampleleSet.iterator().next();
//accessing Set
exampleTable.elements().nextElement();
//accessing Hashtable
// This throws a NoSuchElementException as there are
// no elements in Set and HashTable and we are
// trying to access elements
}
}
// Java program to demonstrate ClassNotFoundException
public class ClassNotFoundException_Demo
{
public static void main(String[] args) {
try{
Class.forName("Class1"); // Class1 is not defined
}
catch(ClassNotFoundException e){
System.out.println(e);
System.out.println("Class Not Found...");
}
}
}
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, users can also create exceptions, which are called ‘user-defined Exceptions’.
The following steps are followed for the creation of a user-defined Exception.
class MyException extends Exception
MyException(){}
MyException(String str)
{
super(str);
}
MyException me = new MyException(“Exception details”);
throw me;
// Java program to demonstrate user defined exception
// This program throws an exception whenever balance
// amount is below Rs 1000
class MyException extends Exception
{
//store account information
private static int accno[] = {1001, 1002, 1003, 1004};
private static String name[] =
{"Nish", "Shubh", "Sush", "Abhi", "Akash"};
private static double bal[] =
{10000.00, 12000.00, 5600.0, 999.00, 1100.55};
// default constructor
MyException() { }
// parameterized constructor
MyException(String str) { super(str); }
// write main()
public static void main(String[] args)
{
try {
// display the heading for the table
System.out.println("ACCNO" + "\t" + "CUSTOMER" +
"\t" + "BALANCE");
// display the actual account information
for (int i = 0; i < 5 ; i++)
{
System.out.println(accno[i] + "\t" + name[i] +
"\t" + bal[i]);
// display own exception if balance < 1000
if (bal[i] < 1000)
{
MyException me =
new MyException("Balance is less than 1000");
throw me;
}
}
} //end of try
catch (MyException e) {
e.printStackTrace();
}
}
}
1. try: The try block contains a set of statements where an exception can occur.
try
{
// statement(s) that might cause exception
}
2. catch: The catch block is used to handle the uncertain condition of a try block. A try block is always followed by a catch block, which handles the exception that occurs in the associated try block.
catch
{
// statement(s) that handle an exception
// examples, closing a connection, closing
// file, exiting the process after writing
// details to a log file.
}
3. throw: The throw keyword is used to transfer control from the try block to the catch block.
4. throws: The throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself.
5. finally: It is executed after the catch block. We use it to put some common code (to be executed irrespective of whether an exception has occurred or not ) when there are multiple catch blocks.
Example of an exception generated by the system is given below :
Exception in thread "main"
java.lang.ArithmeticException: divide
by zero at ExceptionDemo.main(ExceptionDemo.java:5)
ExceptionDemo: The class name
main:The method name
ExceptionDemo.java:The file name
java:5:line number
// Java program to demonstrate working of try,
// catch and finally
class Division {
public static void main(String[] args)
{
int a = 10, b = 5, c = 5, result;
try {
result = a / (b - c);
System.out.println("result" + result);
}
catch (ArithmeticException e) {
System.out.println("Exception caught:Division by zero");
}
finally {
System.out.println("I am in final block");
}
}
}
Output:
Exception caught:Division by zero
I am in final block
// Java program to demonstrate working of throws
class ThrowsExecp {
// This method throws an exception
// to be handled
// by caller or caller
// of caller and so on.
static void fun() throws IllegalAccessException
{
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}
// This is a caller function
public static void main(String args[])
{
try {
fun();
}
catch (IllegalAccessException e) {
System.out.println("caught in main.");
}
}
}
Output:
Inside fun().
caught in main.
1. Exception occurs in try block and handled in catch block: If a statement in try block raised an exception, then the rest of the try block doesn’t execute and control passes to the corresponding catch block. After executing the catch block, the control will be transferred to finally block(if present) and then the rest program will be executed.
// Java program to demonstrate
// control flow of try-catch clause
// when exception occur in try block
// and handled in catch block
class GFG
{
public static void main (String[] args)
{
// array of size 4.
int[] arr = new int[4];
try
{
int i = arr[4];
// this statement will never execute
// as exception is raised by above statement
System.out.println("Inside try block");
}
catch(ArrayIndexOutOfBoundsException ex)
{
System.out.println("Exception caught in Catch block");
}
// rest program will be executed
System.out.println("Outside try-catch clause");
}
}
Output:
Exception caught in Catch block
Outside try-catch clause
// Java program to demonstrate
// control flow of try-catch-finally clause
// when exception occur in try block
// and handled in catch block
class GFG
{
public static void main (String[] args)
{
// array of size 4.
int[] arr = new int[4];
try
{
int i = arr[4];
// this statement will never execute
// as exception is raised by above statement
System.out.println("Inside try block");
}
catch(ArrayIndexOutOfBoundsException ex)
{
System.out.println("Exception caught in catch block");
}
finally
{
System.out.println("finally block executed");
}
// rest program will be executed
System.out.println("Outside try-catch-finally clause");
}
}
Output:
Exception caught in catch block
finally block executed
Outside try-catch-finally clause
2. Exception occurred in try-block is not handled in catch block: In this case, default handling mechanism is followed. If finally block is present, it will be executed followed by default handling mechanism.
// Java program to demonstrate
// control flow of try-catch clause
// when exception occurs in try block
// but not handled in catch block
class GFG
{
public static void main (String[] args)
{
// array of size 4.
int[] arr = new int[4];
try
{
int i = arr[4];
// this statement will never execute
// as exception is raised by above statement
System.out.println("Inside try block");
}
// not a appropriate handler
catch(NullPointerException ex)
{
System.out.println("Exception has been caught");
}
// rest program will not execute
System.out.println("Outside try-catch clause");
}
}
Output:
Runtime Error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at GFG.main(GFG.java:12)
// Java program to demonstrate
// control flow of try-catch-finally clause
// when exception occur in try block
// but not handled in catch block
class GFG
{
public static void main (String[] args)
{
// array of size 4.
int[] arr = new int[4];
try
{
int i = arr[4];
// this statement will never execute
// as exception is raised by above statement
System.out.println("Inside try block");
}
// not a appropriate handler
catch(NullPointerException ex)
{
System.out.println("Exception has been caught");
}
finally
{
System.out.println("finally block executed");
}
// rest program will not execute
System.out.println("Outside try-catch-finally clause");
}
}
Output:
finally block executed
Run Time error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at GFG.main(GFG.java:12)
3. Exception doesn’t occur in try-block: In this case catch block never runs as they are only meant to be run when an exception occurs. finally block(if present) will be executed followed by rest of the program.
// Java program to demonstrate try-catch
// when an exception doesn't occurred in try block
class GFG
{
public static void main (String[] args)
{
try
{
String str = "123";
int num = Integer.parseInt(str);
// this statement will execute
// as no any exception is raised by above statement
System.out.println("Inside try block");
}
catch(NumberFormatException ex)
{
System.out.println("catch block executed...");
}
System.out.println("Outside try-catch clause");
}
}
Output:
Inside try block
Outside try-catch clause
// Java program to demonstrate try-catch-finally
// when exception doesn't occurred in try block
class GFG
{
public static void main (String[] args)
{
try
{
String str = "123";
int num = Integer.parseInt(str);
// this statement will execute
// as no any exception is raised by above statement
System.out.println("try block fully executed");
}
catch(NumberFormatException ex)
{
System.out.println("catch block executed...");
}
finally
{
System.out.println("finally block executed");
}
System.out.println("Outside try-catch-finally clause");
}
}
Output:
try block fully executed
finally block executed
Outside try-catch clause
In this case, no matter whether an exception occur in try-block or not, finally will always be executed. But control flow will depend on whether exception has occurred in try block or not.
1. Exception raised: If an exception has occurred in try block then control flow will be finally block followed by default exception handling mechanism.
// Java program to demonstrate
// control flow of try-finally clause
// when exception occur in try block
class GFG
{
public static void main (String[] args)
{
// array of size 4.
int[] arr = new int[4];
try
{
int i = arr[4];
// this statement will never execute
// as exception is raised by above statement
System.out.println("Inside try block");
}
finally
{
System.out.println("finally block executed");
}
// rest program will not execute
System.out.println("Outside try-finally clause");
}
}
Output:
finally block executed
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at GFG.main(GFG.java:11)
2. Exception not raised: If an exception does not occur in try block then control flow will be finally block followed by rest of the program
// Java program to demonstrate
// control flow of try-finally clause
// when exception doesn't occur in try block
class GFG
{
public static void main (String[] args)
{
try
{
String str = "123";
int num = Integer.parseInt(str);
// this statement will execute
// as no any exception is raised by above statement
System.out.println("Inside try block");
}
finally
{
System.out.println("finally block executed");
}
// rest program will be executed
System.out.println("Outside try-finally clause");
}
}
Output:
Inside try block
finally block executed
Outside try-finally clause
The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions.
throw Instance
Example:
throw new ArithmeticException("/ by zero");
But this exception i.e, Instance must be of type Throwable or a subclass of Throwable. For example Exception is a sub-class of Throwable and user defined exceptions typically extend Exception class. Unlike C++, data types such as int, char, floats or non-throwable classes cannot be used as exceptions.
The flow of execution of the program stops immediately after the throw statement is executed and the nearest enclosing try block is checked to see if it has a catch statement that matches the type of exception. If it finds a match, controlled is transferred to that statement otherwise next enclosing try block is checked and so on. If no matching catch is found then the default exception handler will halt the program.
// Java program that demonstrates the use of throw
class ThrowExcep
{
static void fun()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside fun().");
throw e; // rethrowing the exception
}
}
public static void main(String args[])
{
try
{
fun();
}
catch(NullPointerException e)
{
System.out.println("Caught in main.");
}
}
}
Output:
Caught inside fun().
Caught in main.
throws is a keyword in Java which is used in the signature of method to indicate that this method might throw one of the listed type exceptions. The caller to these methods has to handle the exception using a try-catch block.
type method_name(parameters) throws exception_list
exception_list is a comma separated list of all the
exceptions which a method might throw.
In a program, if there is a chance of raising an exception then compiler always warn us about it and compulsorily we should handle that checked exception, Otherwise we will get compile time error saying unreported exception XXX must be caught or declared to be thrown. To prevent this compile time error we can handle the exception in two ways:
We can use throws keyword to delegate the responsibility of exception handling to the caller (It may be a method or JVM) then caller method is responsible to handle that exception.
// Java program to illustrate error in case
// of unhandled exception
class tst
{
public static void main(String[] args)
{
Thread.sleep(10000);
System.out.println("Hello Geeks");
}
}
Output:
error: unreported exception InterruptedException; must be caught or declared to be thrown
Explanation: In the above program, we are getting compile time error because there is a chance of exception if the main thread is going to sleep, other threads get the chance to execute main() method which will cause InterruptedException.
Important points to remember about throws keyword:
An exception is an issue (run time error) that occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed.
Java provides us the facility to create our own exceptions which are basically derived classes of Exception. Creating our own Exception is known as a custom exception or user-defined exception. Basically, Java custom exceptions are used to customize the exception according to user needs. In simple words, we can say that a User-Defined Exception or custom exception is creating your own exception class and throwing that exception using the ‘throw’ keyword.
For example, MyException in the below code extends the Exception class.
Java exceptions cover almost all the general types of exceptions that may occur in the programming. However, we sometimes need to create custom exceptions.
Following are a few of the reasons to use custom exceptions:
In order to create a custom exception, we need to extend the Exception class that belongs to java.lang package.
Example: We pass the string to the constructor of the superclass- Exception which is obtained using the “getMessage()” function on the object created.
// A Class that represents use-defined exception
class MyException extends Exception {
public MyException(String s)
{
// Call constructor of parent Exception
super(s);
}
}
// A Class that uses above MyException
public class Main {
// Driver Program
public static void main(String args[])
{
try {
// Throw an object of user defined exception
throw new MyException("GeeksGeeks");
}
catch (MyException ex) {
System.out.println("Caught");
// Print the message from MyException object
System.out.println(ex.getMessage());
}
}
}
Output:
Caught
GeeksGeeks
In the above code, the constructor of MyException requires a string as its argument. The string is passed to the parent class Exception’s constructor using super(). The constructor of the Exception class can also be called without a parameter and the call to super is not mandatory.
// A Class that represents use-defined exception
class MyException extends Exception {
}
// A Class that uses above MyException
public class setText {
// Driver Program
public static void main(String args[])
{
try {
// Throw an object of user defined exception
throw new MyException();
}
catch (MyException ex) {
System.out.println("Caught");
System.out.println(ex.getMessage());
}
}
}
Output:
Caught
null