Java Exceptions And Exception Handling With Examples

This Video Tutorial on Java Exceptions Explains all about Exception Handling in Java. You will learn about Exception Hierarchy, Types, Class Methods & more: 

When we are executing Java programs, the normal behavior or normal flow of the program is interrupted, due to some unexpected events.

For example, we open a file for reading the data. When the Open file call is executed, we find the file we are trying to open is missing. This results in the interruption of the normal flow of the program.

This event that affects or interrupts the normal flow of the program is called the “Exception”.

=> Visit Here To Explore The Java Training Series For All.

Java Exceptions and Procedures to Handle Exception

Here is a Video tutorial on Handling Java Exceptions:

Exception Handling In Java

When an exception occurs in the program, the program execution is terminated. As this is an abrupt termination, the system generates a message and displays it. The message generated by the system may be cryptic like some codes or unreadable.

Thus the normal user should understand why the program stopped its execution abruptly, he/she should know the reason. The system generated messages as a result of exception may not be helpful. In Java, we can handle the exception and provide meaningful messages to the user about the issue.

This handling of exception, commonly known as “Exception handling” is one of the salient features of Java programming.

Reasons For The Exception To Occur

We can have various reasons due to which exceptions can occur. If its an exception related to input, then the reason may be that the input data is incorrect or unreadable.

If we get an exception for file I/O then it is quite possible that the files we are dealing with do not exist. At some other time, there may be errors like network issues, printer not available or functioning, etc.

In a program, apart from exceptions, we also get errors. Thus, to handle the exceptions effectively, we need to be aware of the differences between error and an exception.

An error indicates a more serious issue with the application and the application should not attempt to catch it. On the contrary, the exception is a condition that any reasonable application will try to catch.

Thus an error in the application is more severe and the applications would crash when they encounter an error. Exceptions on the other hand occur in code and can be handled by the programmer by providing corrective actions.

What Is Exception Handling?

The Exception Handling in Java is a mechanism using which the normal flow of the application is maintained. To do this, we employ a powerful mechanism to handle runtime errors or exceptions in a program.

A sequence of code that is used to handle the exception is called the “Exception handler”. An exception handler interrogates the context at the point when the exception occurred. This means that it reads the variable values that were in scope while the exception occurred and then restores the Java program to continue with normal flow.

Benefits Of Exception Handling

The major benefit of Exception handling is that it maintains the normal flow of the application despite the occurrence of an exception. When an exception occurs, the program usually terminates abruptly.

Having an exception handler in a program will not cause the program to terminate abruptly. Instead, an exception handler makes sure that all the statements in the program are executed normally and the program flow doesn’t break abruptly.

Exception Hierarchy In Java

The below diagram shows the Exception hierarchy in Java. The class java.lang.Throwable (descendent of Object class) is the root class of Java Exception. The classes Exception and Error are derived from this class.
Exception class is the base class for all the other exceptions.

Given below is a hierarchy of Exception class in Java that will list out all the major exceptions that a Java programmer should be aware of.

Exception class Hierarchy in Java

Exception Class In Java

As seen in the hierarchy diagram, class Throwable has two direct subclasses i.e. Exception and Error. Exceptions arising from an external source are described in the Exception class.

The Exception class declares the constructors as the same as Throwable class and invoking of each constructor also invokes its Throwable counterpart. Exception class does not declare its methods, it inherits Throwable class methods.

The Constructors and Methods that the Exception class uses are presented below.

Constructors

ConstructorDescription
public Exception()A default constructor that constructs a new exception with the message as null.
public Exception(String message)Constructor to construct a new exception with the given message. In this case, the cause is not initialized, and a subsequent call to Throwable.initCause (java.lang.Throwable) may be used to initialize the cause.
public Exception(String message,Throwable cause)Constructs a new exception using a given message and cause.
public Exception(Throwable cause)Constructs a new exception with the given cause and a message given by (cause==null ? null: cause.toString()) (which typically contains the class and detail message of cause).
protected Exception(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace)Constructs a new exception with the given message, cause, suppression (enabled or disabled), and the writable stack trace (enabled or disabled).

Methods

Method PrototypeDescription
public String getMessage()Get a detailed message about the exception that occurred.
public Throwable getCause()Get the cause of the exception represented by a throwable object
public String toString()Concatenates the name of the class with the result of getMessage() and returns the resultant string.
public void printStackTrace()Prints the result of toString() and the contents of stack trace to the error output stream, System.err.
public StackTraceElement [] getStackTrace()Get each element in the stack trace in the form of an array.
public Throwable fillInStackTrace()Fill the stack trace with the current stack trace.

Exception Example

Next, we present a Java program to demonstrate a basic exception example. Here we provide a string variable initialized to a null value. When we try to print this variable, an exception is thrown as the String value cannot be null.

class Main
{ 
    public static void main(String args[]){ 
        	//declare a String variable and initialize it to null  
        	String myStr = null; 
        	//print the string
        	System.out.println(myStr.length()); 
          
    } 
}

Output

Exception example

Types Of Exceptions In Java

Java supports three types of exceptions:

  1. Checked Exception
  2. Unchecked Exception
  3. Error

In this section, we will discuss all the above three types.

#1) Checked Exception

Some exceptions are checked at the compile-time when the code is compiled. These are “Checked exceptions”. The Java program throws a compilation error when it finds that the code inside a program is error-prone.

We can take care of the compilation errors thrown by checked exception by handling the exceptions by either enclosing the code in a try-catch block or using the throws keyword.

In the Exception hierarchy, the class directly inheriting Throwable class like IOException, ClassNotFoundException, etc. are all checked exception except for the classes RuntimeException and Error. These are unchecked exceptions.

The following Java program demonstrates the Checked Exceptions, FileNotFoundException, and IOException. In this program, we try to open a non-existing file and read from it.

As the file does not exist, the open file method throws FileNotFoundException. Next, when we try to read the contents of the file and close the file, the methods calls throw IOException.

import java.io.*;
class Main {  
   public static void main(String args[]) 
   {
	FileInputStream fis = null;
	//Open a file 
       	 fis = new FileInputStream("C:/myfile.txt"); 
	int k; 

	//read contents of the file
    	while(( k = fis.read() ) != -1) 
	{ 
		System.out.print((char)k); 
	} 

	//close the file
	fis.close(); 	
   }
}

Output

Checked Exception - output

In the above output, as the exception handler is absent, we get compilation errors for checked exceptions.

Now let us provide a throws clause for this program. As FileNotFoundException’s parent is IOException, we will just specify the IOException after the throws clause.

import java.io.*;
class Main {  
   public static void main(String args[]) throws IOException
   {
	FileInputStream fis = null;
	//Open a file 
        	fis = new FileInputStream("C:/myfile.txt"); 
	int k; 

	//read contents of the file
   	 while(( k = fis.read() ) != -1) 
	{ 
		System.out.print((char)k); 
	} 
	//close the file
	fis.close(); 	
   }
}

Output

Exception in thread - checked exception

As seen from the output, when we handle the exception, it provides more meaningful output instead of the compilation errors.

#2) Unchecked Exception

Unchecked exceptions are the exceptions that are checked at run time. Hence despite exceptions, a compilation of programs will be successful. Most of the unchecked exceptions are thrown owing to the bad data used in the program.

The classes that inherit “RuntimeException” are unchecked exceptions. Exceptions like ArrayIndexOutofBounds Exception, ArithmeticException, NullPOinterException, etc. are examples of unchecked exceptions.

The following program demonstrates a runtime unchecked exception that is caused by dividing a number by zero.

class Main {  
   public static void main(String args[])
   {
	int num1=10;
	int num2=0;
	//divide both numbers and print the result
	int result=num1/num2;
	System.out.println(result);
   }
}

Output

Unchecked Exception - output

We see that the program is compiled successfully and then the ArithmeticException is thrown at runtime.

Examples of Unchecked Exception:

  • ArrayIndexOutOfBoundsException
  • NullPointerException
  • IllegalArgumentException
  • NumberFormatException

Apart from the above two exceptions, there are few more Checked exceptions including:

  • SQLException
  • InvocationTargetExecption

#3) Error

Error is usually an irreversible and irrecoverable situation in a program and when an error occurs, the programs crash. Some of the examples of errors in a program are OutOfMemoryError, AssertionError, and VirtualMachineError, etc.

Error class inherits from the Throwable class. Error describes a situation that cannot be handled and results in a program crashing.

Let’s discuss the OutOfMemory error in this section as an example of error.

We know that all the objects in Java are allocated using the new operator and are stored on the heap. When the heap goes out of memory, the Java Virtual Machine (JVM) cannot allocate the object. At the same time, the garbage collector cannot free any memory. This situation gives rise to the OutOfMemory error.

The OutOfMemoryError in Java will look as shown below:

"exception in thread \"main\" java.lang.outofmemoryerror: java heap space"

The presence of OutOfMemoryError in a program means either too much data is being processed or the objects are being held for too long. Sometimes, it can also be a third-party library that uses up memory.

Causes Of OutOfMemoryError

#1) Java Heap Space

If an application has too many finalizers, then the class objects having the Finalize method are not reclaimed by garbage collector immediately but are queued up for finalization at a later time. Sometimes, the finalization cannot keep up with time, and heap memory is filled up resulting in OutOfMemoryError.

Another reason for OutOfMemoryError is that the heap size specified may be insufficient for the application.

The following code demonstrates the OutOfMemoryError that can occur because of a huge data size declared for an array.

import java.util.*; 
 public class Main { 
    static List<String> list = new ArrayList<String>(); 
    public static void main(String args[]) throws Exception 
    { 
        Integer[] array = new Integer[100000 * 100000]; 
    } 
}

Output

Java Heap Space Output

#2) Permgen Space

Permanent Generation Area in memory can also be exhausted and could generate OutOfMemory error.

The size of the PermGen region is set during the JVM launch. If the user does not set the size, then the default size that is platform-specific is used.

Though the above two are usually the main causes of OutOfMemoryError occurrence, there may be other causes like Array size exceeding VM limit, etc.

List Of Exceptions In Java

Given below is a list of the major exceptions that occur in Java. We have provided programming examples for some of these exceptions. Note that these are built-in exceptions supported by Java.

#1) ArithmeticException: Arithmetic abnormalities like divide by zero results in ArithmeticException.

The below program demonstrates the occurrence of ArithmeticException.

class Main { 
public static void main(String args[]) 
    { 
        try { 
            //define two numbers 
            int num1 = 100, num2 = 0; 
            int result = num1 / num2; // divide by zero 
            //print the result
            System.out.println("Result = " + result); 
        } 
        catch (ArithmeticException e) { 
            System.out.println("ArithmeticException:Division by Zero"); 
        } 
    } 
}

Output

Arithmetic Exception

#2) ArrayIndexOutOfBoundsException: ArrayIndexOutOfBoundsException is thrown when an array element is accessed using an illegal index. The index used is either beyond the size of the array or is negative.

#3) ClassNotFoundException: If the class definition is not found then the ClassNotFoundException is raised.

#4) FileNotFoundException: FileNotFoundException is given when the file does not exist or does not open.

#5) IOException: IOException is thrown when the input-output operation fails or is interrupted.

#6) InterruptedException: Whenever a thread is doing processing or sleeping or waiting, then it is interrupted by throwing InterruptedException.

#7) NoSuchFieldException: If a class does not contain a specified field or variable, then it throws NoSuchFieldException.

#8) NoSuchMethodException: When the method being accessed is not found, then NoSuchMethodException is raised.

#9) NullPointerException: NullPointerException is raised when a null object is referred. This is the most important and most common exception in Java.

#10) NumberFormatException: This exception is raised when a method could not convert a string into a numeric format.

#11) RuntimeException: Any exception that occurs at runtime is a RuntimeException.

#12) StringIndexOutOfBoundsException: The StringIndexOutOfBoundsException is thrown by String class and indicates that the index is beyond the size of the String object or is negative.

#13) EOFException: EOFException is a part of the java.io package and is thrown when the end of file is reached and the file is being read.

#14) IllegalArgumentException: IllegalArgumentException is thrown when illegal or invalid arguments are passed to the method. For example, the wrong data format, null value when non-null is required or out of range arguments.

The below Java program demonstrates the IllegalArgumentException.

public class Main {
   int m;
   public static void setMarks(int marks) {
      if(marks < 0 || marks > 100)  //throw exception if marks are not in range
         throw new IllegalArgumentException(Integer.toString(marks));
      else
         System.out.println("Marks Entered: " + marks);
   }
   public static void main(String[] args) {
      setMarks(45);
      setMarks(101);
   }
}

Output

IllegalArgumentException - Output

In the above program, the IllegalArgumentException is thrown in the second call to setMarks function where we enter the marks that are out of range (> 45).

#15) InputMismatchException: InputMismatchException is thrown when the input read does not match a pattern specified. For example, if the program expects integer and reads a float, then the InputMismatchException is raised.

#16) NoSuchElementException: NoSuchElementException is thrown when the next element accessed does not exist.

For example, in Enumeration, the nextElement () method is used to access the next element in the enumeration. If the element does not exist, then NoSuchElementException is thrown. Mostly Java Collections throw this exception.

The program given below demonstrates this.

import java.util.*;  
  
public class Main {  
    public static void main(String[] args) {  
         Set hash_Set = new HashSet();  //create an empty hashSet. 
         //This throws NoSuchElementException  since hashSet is empty
         hash_Set.iterator().next();                                
}  
}  

Output

NoSuchElementException - output

#17) ConcurrentModificationException: ConcurrentModificationException is usually thrown by Collection classes. This exception is thrown when the objects try to modify a resource concurrently.

For example, a thread cannot modify a collection when another thread is accessing it. If we allow two threads, then those two will simultaneously access the collection, and there will be inconsistencies.

The following example demonstrates the ConcurrentModificationException.

import java.awt.List;  
import java.util.*;  
  
public class Main {  
     public static void main(String[] args) {  
        ArrayList<Integer> A_list = new ArrayList<>();  
        //add elements to the ArrayList
        A_list.add(10);  
        A_list.add(20);  
        A_list.add(30);  
        Iterator<Integer> it = A_list.iterator();  
        while (it.hasNext()) {                   
            Integer value = it.next();              
            System.out.println("ArrayList Value:" + value);  
            if (value.equals(30))  
                A_list.remove(value);  
        }  
    }  
}  

Output

ConcurrentModificationException - Output

In the above program, while the ArrayList is being printed, we try to delete an element at the same time. This is the concurrent access and thus an exception is thrown.

Custom Exceptions In Java

So far we have discussed all the exceptions that are built-in or provided by Java language. Apart from these exceptions, we can also define our own exceptions. These are called Custom exceptions or user-defined exceptions.

Using custom exceptions, we can define our exceptions as per our needs.

The following example shows the custom exception that we defined for an Integer value.

//custom exception definition
class InvalidValueException extends Exception{  
 InvalidValueException(String s){  
  super(s);  
 }  
}  

class Main{  
    static void validate(int int_val)throws InvalidValueException{  
     if(int_val<10)         //value is valid if > 10 else throw exception
      throw new InvalidValueException("Invalid value");  
     else  
      System.out.println("This is valid integer");  
   }  
     
   public static void main(String args[]){  
      try{  
      validate(9);  
      }catch(Exception m){System.out.println("Exception occured: "+m);}  
  
      System.out.println("Code after Exception");  
  }  
}   

Output

Custom Exception in Java

Frequently Asked Questions

Q #1) What do you mean by exception?

Answer: An event that occurs during the execution of a program and disrupts the normal execution flow of the program is called Exception. The exception is unwanted & unexpected and may occur owing to external factors or programming errors.

Q #2) What is the difference between Error and Exception?

Answer: Exceptions are events that disrupt the normal flow of the program. We can handle exceptions in our program and continue with the program normally. An error is an irrecoverable event that cannot be handled and terminates the program.

Q #3) What do you mean by Exception Handling?

Answer: The process of specifying the sequence of steps in a program to handle the exception is called Exception Handling. By providing exception handlers in a program, we can ensure the normal flow of the program.

Q #4) What are the advantages of Exception Handling in Java?

Answer: Using exception handling we can maintain the normal flow of execution of an application. We can also propagate the errors up the call stack when we provide exception handlers.

Q #5) What is the use of Exception Handling?

Answer: Not terminating the normal flow of execution of an application is the major use of having exception handlers in a program. Without exception handlers, the program will terminate and the normal execution flow will be interrupted when an exception occurs.

With exception properly handled in the program, it can continue with its normal execution even when an exception occurs.

More Examples On Exceptions

An exception is an event that occurs while the program is running and it disrupts the program execution. Because of which the software product will end abruptly.

When this exception occurs, Java creates an object with an error message and information about the class. This is the exception object.

Why we need an Exception in Java?

Class ExcepDemo without Exception:

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

int i=5;
int j=0;
System.out.println(i/j);

System.out.println("statement after division");
}
} 

Class ExcepDemo without Exception

OUTPUT:

output- Java Class ExcepDemo without Exception

Class ExcepDemo with Exception Handling:

 public class ExcepDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i=5;
int j=0;
try {

System.out.println(i/j);
}
catch(ArithmeticException ae) {

System.out.println("wrong input");
}
System.out.println("statement after division");
}

} 

Java Class ExcepDemo with Exception Handling

OUTPUT:

output- Class ExcepDemo with Exception Handling

Try, catch and finally block:

  • An exception is handled by try, catch block.
  • Statements which can lead to exceptions are written inside the try block.
  • When an exception occurs, the statements inside the catch block will be executed. If an exception does not occur, the catch block will not be executed.
  • Irrespective of exception occurred or not occurred, the final block will be executed.

Exception Types

Unchecked Exception:

As Unchecked exceptions can be avoided by the proper programming (E.g. null pointer Exception, Arithmetic Exception)  will not have checked by the compiler. Unchecked Exception will be thrown at runtime.

Checked Exception:

  • Checked Exception will be checked by the compiler and its mandatory to throw or handle the exception.
  • This Exception is used to separate the error handling code from the regular code.
  • All the checked exceptions are grouped and it is useful in differentiating the problems.

Example: java.io

 import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class DemoExpChecked {

public static void main(String[] args)
{

try {
File file=new File("input.txt");
 
BufferedReader br = new BufferedReader(new FileReader(file)) ;
String content;
while ((content=br.readLine())!=null)
  {
    System.out.println(content);
  }
  br.close();

}
catch(IOException e) {
e.printStackTrace();
}
}
} 

Checked Java Exception

Errors

An error can occur due to program logical mistakes or any memory related to JVM problem.

Example: Memory out of bound error or stack overflow error.

Throw and Throws

“Throw” keyword is used to throw the exception, whereas the “throws “keyword is used to declare the exception.

Throw Example Program:

 public class Demothrow {
String content ;
public void driving(String c) {
this.content=c;
if (content.isEmpty())
{
throw new NullPointerException("content is empty");
}
else {
System.out.println("content=="+content);
}
}
public static void main(String[] args) {
Demothrow dt=new Demothrow();

dt.driving("");
}
} 

Throw and throws

Throws Example Program:

Throws are used to give information that this method throws this particular exception. When you call that particular method, you need to handle that exception.

 public class DemoThrows {
int i=2,j=0;
public void checkmethod () throws ArithmeticException{
System.out.println(i/j);
}

public static void main(String[]
args) {

DemoThrows d =new DemoThrows();

try {
d.checkmethod();
}
catch (ArithmeticException ae) {

ae.printStackTrace();
}

}
} 

Throws Example

Key points to be noted:

  • Exceptions are abnormal events that are occurred during the program execution and it will affect the execution flow.
  • An error is different from exceptions. Errors Example: Memory out of error.
  • Checked exceptions are checked during compilation and it is mandatory to deal with this checked exception.
  • An unchecked exception occurs during the runtime.

Conclusion

This tutorial on Exception handling in Java introduced the definition of exceptions, exception handling, and the exception hierarchy in Java. We also discussed the exception class in Java that provides various constructors and methods to access exceptions.

We explored a list of the common exceptions that occur in Java and saw the programming examples for the major exception. We also discussed the major errors that occur in a Java program along with the types of exceptions and custom exceptions.

=> Check ALL Java Tutorials Here.