• Articles
  • Tutorials
  • Interview Questions

Exception Handling in Java - A Comprehensive Guide

Introduction to Exception Handling in Java

This topic introduces the basic concept of Exception Handling in Java.
As you know, Nobody is perfect in this world. So, what if you are driving a car and suddenly something happens and the car stopped? How will you handle that situation?
Say the reason is “No Fuel”.
Exception handling
Similarly, while writing a program, if JVM finds something unacceptable then, it throws exceptions.
In this tutorial, you will learn about Exceptions and how to handle those exceptions.

Watch this Java video by Intellipaat:

Video Thumbnail

Here are the topics if you directly want to jump:

What is an Exception in Java?

An Exception is an event that occurs during the execution of a program and it interrupts the normal flow of program executions.
Example:What is an Exception
Let’s say two persons orders Pine-Apple juice in a juice shop and the order came out to be Orange juice. This is a case of exception in java.

Some common problems which may cause exception:

  • Creating array object with negative size.
  • Accessing index of array which is not available
  • Dividing an integer value with zero.
  • Invoking instance members with null reference.
  • Recursive method invocation without conditional check.
public class ExceptionTest{
public static void main(String args[]){
System.out.println(“Main Started”);
String data= args[0]; //value at command line to variable
int x= Integer.parseInt(data); // to convert string value into int type
int res=10/x;
System.out.println(res);
}
}
  • The code will be compiled successfully.
  • While executing, JVM will use some threading concept to process the task like verify the class file, main method, etc.
  • After verifying the class and the required main method JVM will invoke the main method.
  • JVM will process the statements available in the main method one by one.

Case 1:  java ExceptionTest (when value not provided from command line)
Main Started
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException:0
Case 2:  java ExceptionTest Intellipaat (when string value is converted to int type)
Main Started
Exception in thread “main” java.lang.NumberFormatException:For input string:”Intellipaat”
Case 3:  java ExceptionTest 0 (when 0 is provided from command line)
Main Started
Exception in thread “main” java.lang.ArithmeticException: / by zero
When a statement causes the problem then JVM will do the following tasks:

  • Analyze the problem.
  • Identify the class define in java language (may be exception or error)
  • Create the object of identified class with required message.
  • Throw the object(raise the event).

Once the object is thrown(event generated)

  • JVM will verify that any statement is available in the current block to catch the object or not.
  • If no statement found the control will be transferred to the caller method.
  • In the above program, the caller of main() method is JVM, so control will be transferred to JVM.
  • JVM will use default event handler to handle the event. The default handler will print the message to the console.
  • If JVM will handle the exception then program execution will be terminated abnormally.

When to use Exception Handling in Java?

If you want to catch the exception explicitly so that other statements from your application can be executed successfully, then you need to use an exception handler in your program.
Problem Types
When to use exception handling
Problem that occurred while executing the statement can be divided into two types:

  • Error
  • Exception

Error

  • It is a type of problem that will not be handled and the execution of the application will be terminated.
  • Depending on the reason, various classes are defined for various errors and all the error classes are subclasses of java.lang.Error class.

Handling Exception in Java program

  • You can use try and catch blocks to handle the exception.

exception

Certification in Bigdata Analytics

Try and Catch Block

  • Try block should be followed by zero or more catch blocks.
  • When you expect the problems with any java statements, then place those statements inside the try block.
  • When exception is raised with the try block statements, then control will be transferred to the corresponding catch block.
  • Catch block should contain statements to handle the exceptions raised by the try block statements.

Syntax:

try{
// statements
} catch(){
// statements
}
  • You can write multiple catch block for one try block to handle each exceptions separately.
try{
// statements
} catch(){
// statements
}catch(){
// statements
}
…..
public class ExceptionTest{
public static void main(String args[]){
System.out.println(“Main Started”);
int x=Integer.parseInt(args[o]);
try{
int res=10/x;
System.out.println(res);
} catch(Exception e){
System.out.println(“Enter correct value”);
}
}
}

In the above program:
Case 1:
java ExceptionTest 1 (enter value of x as 1 from command line)
10
Case 2:
java ExceptionTest 0 (enter value of x as 0 from command line)
Enter correct value

Get 100% Hike!

Master Most in Demand Skills Now!

Finally Block

Finally block
There are some cases in which statements after catch block will not be executed:

  • When you have return statement inside the try and catch block.
  • When exception occurs in the try block and matching catch block is not found.
  • When exception occurs in the catch block, etc.

If you want to execute statements after catch block which fails to execute, then you have those statements in the finally block.
Syntax:

try{
// statements
} catch(){
// statements
}finally{
//statements
}

Program to understand finally block

public class ExceptionTest{
public static void main(String args[]){
System.out.println(“Main Started”);
int x=Integer.parseInt(args[o]);
try{
int res=10/x;
System.out.println(res);
} catch(Exception e){
System.out.println(“Enter correct value”);
}
}finally{
System.out.println(“Main Completed”);
}} }

In the above program, finally block will be executed always.

Types of Exception in Java

There are two types of exceptions:

  • Checked exceptions
  • Unchecked exceptions

Types of exception

Checked Exception

  • These are also called compile time exceptions.
  • All the subclasses of java.lang.Exception except java.lang.RuntimeException and its sub classes are checked exception.
  • In other words, if you have any java statement that may cause any exception and that exception is verified by the compiler by forcing you to report the exceptions are called checked exceptions.
  • Checked Exception must be reported in any one of the two ways:
    • Using try-catch block
    • Propagating the exception using throws
  • If you are not reporting checked exception then you will get the following error message at compile time:

Unreported exception <ExceptionName>; must be caught or declared to be thrown.

public class Intellipaat{
public static void main(String args[]){
System.out.println(“Main Started”);
Intellipaat i=new Intellipaat();
Object obj=i.clone();
System.out.println(“main completed”);}
}}

Output:
Unreported exception
CloneNotSupportedException; must be caught or declared to be thrown

Unchecked Exception

  • These are also called as runtime exceptions.
  • lang.RuntimeException and its subclasses are unchecked exceptions.
  • If you have any java statement that may cause any exception and that exception is not verified by the compiler at compile time, then those exceptions are called as unchecked exceptions.
  • In case of unchecked exception, compiler is not responsible to verify whether you are reporting about the exception or not, i.e. unchecked exceptions may or may not be reported.

Throw keyword

  • throw is a keyword used to throw exceptions explicitly.
  • You can throw any checked or unchecked exceptions.
  • You can throw any built-in or user-defined exceptions.

Syntax:
throw <throwableTypeObjectRef>
Example:
throw new NullPointerException();
throw new StudentNotFoundException();

class ThrowCheck{
static void show(){
try{
throw new NullPointerException("check");
}catch(NullPointerException ex)
{System.out.println("show() has throw");
throw ex; // rethrowing the exception
}
}public static void main(String args[]){
try{
show();
}catch(NullPointerException ex)
{
System.out.println("Exception in main found");
}
}
}

Output:
show() has throw
Exception in main found

Throws keyword

  • throws is a keyword used to propagate the exceptions to the caller method by specifying at method level.
  • You can define any checked or unchecked exceptions at method level.
  • You can define any built-in or user defined exceptions at method level.
  • When the exception is unchecked, then throws keyword is optional. But for checked exception throws keyword is mandatory.
class Throwscheck
{
static void show() throws IllegalAccessException
{
System.out.println("show() has exception ");
throw new IllegalAccessException("demo");
}
public static void main(String args[]){
try
{
show();
}
catch(IllegalAccessException ex)
{
System.out.println("main() has show()");
}
}
}

Output:
show() has exception
main() has show()

Become a Big Data Architect

User Defined Exception

The exceptions which are defined and implemented by application developer as per project requirements are called user defined exceptions.

Example:
StudentNotFoundException
InvalidDetailsException
UnsuccessfulAttemptsException

class UserCheck extends Exception{public UserCheck(String s)
{
super(s);
}
}public class Intellipaat{
public static void main(String args[])
{
try{
throw new UserCheck("Intellipaat");
} catch (UserCheck ex)
{
System.out.println("caught exception");
System.out.println(ex.getMessage());
}
}
}

Output:
caught exception
Intellipaat

Conclusion

This brings us to the end of our discussion on exception handling. In this tutorial, we have learned in detail about the overview of exception handling in Java.

We have also covered almost all of the main parts of exception handling. If you want to learn more, I would suggest trying our Intellipaat Java course, which covers in-depth knowledge of most of the important topics in Java, such as basics, arrays, exception handling, multithreading, and more. This will help you become a good Java programmer.

Join the Intellipaat Java training course and certification today, and let your career soar toward the realm of software development.

Course Schedule

Name Date Details
Python Course 30 Nov 2024(Sat-Sun) Weekend Batch View Details
07 Dec 2024(Sat-Sun) Weekend Batch
14 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration.