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.
Java
    • The code will be compiled successfully.
    • While executing, JVM will use some threading concepts to process the task like verifying 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 the 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 a problem then JVM will do the following tasks:

  • Analyze the problem.
  • Identify the class defined in Java language (maybe exception or error)
  • Create the object of an identified class with a required message.
  • Throw the object(raise the event).

Once the object is thrown(event generated)

  • JVM will verify whether any statement is available in the current block to catch the object or not.
  • If no statement is found the control will be transferred to the caller method.
  • In the above program, the caller of the main() method is JVM, so control will be transferred to JVM.
  • JVM will use the 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
A 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 problems with any Java statements, then place those statements inside the try block.
  • When an exception is raised with the try block statements, then control will be transferred to the corresponding catch block.
  • The 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
}
...
Java
  • 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

    Java

    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.

    Java

    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();

    Java

    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.
    Java

    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

    Java

    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.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.