Browse Tutorials
Exception handling in Java: Try, Catch, Finally, Throw and Throws

Exception handling in Java: Try, Catch, Finally, Throw and Throws

12 Apr 2024
Intermediate
2.25K Views
26 min read
Learn via Video Course & by Doing Hands-on Labs

Java Programming For Beginners Free Course

Exception Handling in Java: An Overview

Exception Handling in Java deals with the techniques to deal with unwanted and unexpected events occurring during the program execution. With learning Java, one must be ready to deal with errors, unexpected inputs, or other exceptions. In this blog post on Java tutorial, we'll discuss how to use Java's tools for exception handling. To increase your knowledge of Java you can also take our Java Programming Course.

What is Exception Handling in Java?

Exception handling in Java is an unwanted event that happens during the program's execution. How to handle an exception in Java can be answered by using jump statements in Java, which involve terminating the program or affecting the flow of the program.

Various reasons cause exception handling in Java, such as:

  • Device failure
  • Loss of network connection
  • Invalid user input
  • Code errors
  • Opening an unavailable file
  • Physical limitations

Why Handle Java Exception?

If you want your Java programs to run smoothly, you need to handle the exceptions raised in between the execution process. If you don't do that, your programs can crash in between the execution on encountering exceptions. These exceptions are runtime as well as compile-time. A minute exception is capable of crashing your program execution, hence it becomes necessary to handle Java exceptions.

Let's look at an example where the program has some lines of code. There's an exception in one of its lines which abruptly ends the program execution


class ExceptionExample {
  public static void main(String args[]) {
    System.out.println("Welcome to ScholarHat");
    int a = 30;
    int b = 0;
    System.out.println(a / b);
    System.out.println("Welcome to the ScholarHat's Java Programming tutorial.");
    System.out.println("Enjoy your learning");
  }
}

Output

Welcome to ScholarHat

Exception in thread "main" java.lang.ArithmeticException: / by zero
	at ExceptionExample.main(ExceptionExample.java:6)

In the above code, at the 4th line, an integer is divided by 0, which is not possible, and an exception is raised by JVM(Java Virtual Machine). In this case, the exception is not handled by the programmer which will halt the program in between by throwing the exception, and the rest of the lines of code won't be executed.

Read More - Top 50 Java Interview Questions

Types of Exceptions in Java

There are three types of exception handling in Java, which are

  1. Unchecked or Runtime Exceptions in Java
  2. Checked or Compile-time Exceptions in Java
  3. Errors in Java

Types of Exceptions in Java

1.) Runtime Exceptions or Unchecked Exceptions in Java

Runtime Exception or unchecked exception in Java happens because of the error in coding involving Strings in Java. This is also called an unchecked exception because it is not checked at compile time, but it is checked at Runtime.

Some Runtime Exception is,

  • Null pointer
  • Out-of-bounds array access
  • Dividing a number by 0
  • Improper use of an API

2.) Compile Time Exceptions or Checked Exceptions in Java

Compile time exceptions are handled by the compiler so that it is called a checked exception. There are some examples of checked exceptions, those are

  • Read past the end of a file
  • Open a file that does not exist

3.) Errors in Java

  • Java errors are essential for identifying problems with program execution.
  • They are essential to debugging since they help developers find and fix issues.
  • Error exceptions are specific and provide problem descriptions, which makes it easier to identify errors.
  • Error exceptions give developers an organized way to handle problems, preventing them from having to start over.
  • The "catch" keyword allows for the quick detection of errors and subsequent corrective action.
  • Error exceptions can have several causes, including memory leaks, problems with input validation, and server troubles.
  • Java errors assist in real-time debugging during software development, regardless of the reason.
  • They help in the early identification of potential problems before the deployment of programs by preventing catastrophic errors during testing.

Read More - Java Certification Salary

Difference Between Checked and Unchecked Exceptions

Checked ExceptionUnchecked Exception
Occur at compile time.Occur at runtime.
The compiler checks for checked exceptions.The compiler does not check for unchecked exceptions.
If checked exceptions are not handled we get a compile-time error.If unchecked exceptions are not handled we get a run time error.
Can be handled at compile time.Can not be caught/handled at runtime.
They are direct subclasses of the exception class but do not inherit the Runtime Exception Class.They are subclasses of the Runtime Exception class.
Eg: IOException, ClassNotFoundException, SQLException, etcEg: ArithmeticException, NullPointerException, NumberFormatException, StringIndexOutOfBoundException, ArrayIndexOutOfBoundException, etc.

Exception Hierarchy in Java

Exception hierarchy in Java can be defined by this picture:

Exception Hierarchy in Java

How does JVM handle an Exception?

The exceptions in Java that are raised during the program execution are objects of the respective exception class in the hierarchy shown above. The exceptions have a naming and inheritance hierarchy to the main exception class in Java i.e. Throwable class. All Java exception objects include the toString() method, which outputs the fully qualified name of the exception class. This functionality aids in understanding the exceptional conditions encountered during program execution.

Whenever an exception has occurred inside a method, the method creates an exception object and hands it over to JVM. This object contains the name and description of the exception and the current state of the program where the exception has occurred. This is called the process of object creation and handing it over to JVM is known as throwing an Exception. This object is an exception that is further handled by JVM.

When an exception occurs, the JVM maintains an ordered list of the methods that were called leading up to the point where the exception was raised. This list is referred to as the Call Stack.

The JVM traverses this call stack to identify the method where the exception originated. It searches for the appropriate code block, known as an Exception handler, to address the encountered exception. Once an appropriate handler is located, the JVM manages the exception according to the code within the handler and provides feedback on the program's state.

Example in our Java Compiler


class SampleException {
  public static void main(String args[]) {
    int a = 30;
    int b = 0;
    System.out.println(a / b);
  }
}

Output

Exception in thread "main" java.lang.ArithmeticException: / by zero
	at SampleException.main(SampleException.java:5)

How to handle Exceptions in Java?

Customized exception handling in Java is achieved using five keywords:

  1. try
  2. catch
  3. throw
  4. throws
  5. finally

Java Exception Keywords and Examples

  1. try
    • try block consists of all the doubtful statements that can throw exceptions.
    • It can have multiple statements.
    • A try block cannot be executed on itself, it requires at least one catch block or finally block.
    • When any exception occurs in a try block, the appropriate exception object will be redirected to the catch block, this catch block will handle the exception according to statements in it and continue the further execution.
    • The control of execution goes from the try block to the catch block once an exception occurs.

    Syntax

    
    try
    {
     //Doubtful Statements.
    }
    
  2. catch
    • catch block consists of the solution or alternative for an exception.
    • It is used to handle the exception by declaring the type of exception within the parameter.
    • The declared exception must be the parent class exception or the generated exception type in the exception class hierarchy or a user-defined exception.
    • There can be multiple catch blocks with a single try block.

    Syntax

    
    try
     {
      // code
     }
     catch(Exception e)
     {
      // code
     }
    
  3. Examples illustrating try-catch block usage in Java Exception Handling in Java Online Compiler

    1. try-catch block
      
      class Main
      {
        public static void main(String[] args)
        {
         try
         {
          // code that generate exception
          int divideByZero = 5 / 0;
          System.out.println("Rest of code in try block");
         }
         catch (ArithmeticException e) {
          System.out.println("ArithmeticException => " + e.getMessage());
         }
        }
       }

      This Java example shows how to handle exceptions. It tries to divide by zero, resulting in an ArithmeticException handled in the catch block and outputs an error.

      Output

      ArithmeticException => / by zero
      
    2. Multiple Catch Blocks
      
      public class MultipleCatchBlock {
      
        public static void main(String[] args) {
      
          try {
            int x[] = new int[5];
            x[5] = 40 / 0;
          } catch (ArithmeticException e) {
            System.out.println("Arithmetic Exception occurs");
          } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("ArrayIndexOutOfBounds Exception occurs");
          } catch (Exception e) {
            System.out.println("Parent Exception occurs");
          }
          System.out.println("The program ends here");
        }
      }
      

      After execution of the try block, the Arithmetic Exception is raised and JVM starts to search for the catch block to handle the same. JVM will find the first catch block that can handle the raised exception, and control will be passed to that catch block.

      Output

      Arithmetic Exception occurs
      The program ends here
      
    3. Nested Try Catch
      
      class NestingTry {
        public static void main(String args[]) {
          //main try-block
          try {
            //try-block2
            try {
              //try-block3
              try {
                int arr[] = {
                  10,
                  20,
                  30,
                  40
                };
               
                System.out.println(arr[10]);
              } catch (ArithmeticException e) {
                System.out.print("Arithmetic Exception");
                System.out.println(" handled in try-block3");
              }
            } catch (ArithmeticException e) {
              System.out.print("Arithmetic Exception");
              System.out.println(" handled in try-block2");
            }
          } catch (ArithmeticException e3) {
            System.out.print("Arithmetic Exception");
            System.out.println(" handled in main try-block");
          } catch (ArrayIndexOutOfBoundsException e4) {
            System.out.print("ArrayIndexOutOfBoundsException");
            System.out.println(" handled in main try-block");
          } catch (Exception e5) {
            System.out.print("Exception");
            System.out.println(" handled in main try-block");
          }
        }
      }
      

      In the above code, the ArrayIndexOutOfBoundsException occurred in the grandchild try-block3. Since try-block3 is not handling this exception, the control then gets transferred to the parent try-block2. Since the try-block2 is also not handling that exception, the control gets transferred to the main try-block where it finds the appropriate catch block for an exception.

      Output

      ArrayIndexOutOfBoundsException handled in main try-block
      
  4. finally

    Finally block in Java always executes even if there are no exceptions. This is an optional block. It is used to execute important statements such as closing statements, release resources, and release memory. For every try block, there could be one final block. This Finally block executes after try..catch block.

    Syntax

    
    try
     {
      //code
     }
     catch (ExceptionType1 e1)
     {
      // catch block
     }
     finally
     {
      // finally block always executes
     }
    

    Example: Java Exception Handling using finally block in Java Playground

    
    class Main
    {
      public static void main(String[] args)
      {
       try
       {
        // code that generates exception
        int divideByZero = 5 / 0;
       }
       catch (ArithmeticException e)
       {
        System.out.println("ArithmeticException => " + e.getMessage());
       }
       finally
       {
        System.out.println("This is the finally block");
       }
      }
     }

    In this Java example, trying to divide by zero results in an ArithmeticException that is caught and accompanied by an error message. The "finally" block also always runs, printing "This is the finally block" whether or not an exception was raised.

    Output

    ArithmeticException => / by zero
    This is the finally block
    
  5. Java Final Vs Finally Vs Finalize

    finalfinallyfinalize
    final is the keyword and access modifierfinally block is used in Java Exception Handling to execute the important code after try-catch blocksfinalize is the method in Java.
    final access modifier is used to apply restrictions on the variables, methods, classes.finally block executes whether an exception occurs or not. It is used to close resources.finalize() method is used to perform clean-up processing just before an object is garbage collected.
    It is used with variables, methods, and classes.It is with the try-catch block in exception handling.Used with objects
    Once declared, the final variable becomes constant and can't be modifiedfinally block cleans up all the resources used in the try blockfinalize method performs the cleaning concerning object before its destruction
    final is executed only when we call itfinally block executes as soon as the execution of try-catch block is completed without depending on the exceptionfinalize method is executed just before the object is destroyed
  6. throw
    • throw keyword is used to throw an exception explicitly.
    • Using the throw keyword, We can throw checked as well as unchecked exceptions.
    • We specify the class of exception object which is to be thrown. The exception has some error message with it that provides the error description.
    • We can also define our own set of conditions for which we can throw an exception explicitly using the throw keyword.
    • The flow of execution of the program stops immediately after the throw statement is executed and the nearest try block is checked to see if it has a catch statement that matches the type of exception.
    • It tries to find all the catch blocks until it finds the respective handler, else it transfers the control to the default handler which will halt the program.

    Syntax

    
    throw new exception_class("error message");
    

    Example: Exception handling using Java throw

    
    class Main
    {
      public static void divideByZero()
      {
       // throw an exception
       throw new ArithmeticException("Trying to divide by 0");
      }
      public static void main(String[] args)
      {
       divideByZero();
      }
     }

    This Java example in our Java Online Editor develops a method 'divideByZero()' that is invoked in the main method and purposefully raises an ArithmeticException with a customized message. It raises the exception with the provided message when it is run.

    Output

    Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0
        at Main.divideByZero(Main.java:5)
        at Main.main(Main.java:9)
  7. throws
    • throws keyword is used in the signature of the method to indicate that this method might throw one of the exceptions from the Java exception class hierarchy.
    • throws keyword is used only for checked exceptions because Unchecked exceptions can be avoided by correcting the programming mistakes.
    • throws keyword can be used to declare an exception.
    
    import java.io.IOException;
    
    public class ThrowsExample {
    
        public static void main(String[] args) {
            try {
                methodWithException();
            } catch (IOException e) {
                System.out.println("Caught IOException: " + e.getMessage());
            }
        }
    
        public static void methodWithException() throws IOException {
            // Simulate an IOException
            throw new IOException("This is an IOException");
        }
    }
    

    In the above code, the methodWithException method does not handle the exception internally but declares that it may throw it, allowing the caller to handle it instead.

    Output

    Caught IOException: This is an IOException
    
  8. Throw Vs Throws

    throwthrows
    Java throw keyword is used to throw an exception explicitly in the program, inside any block of codeJava throws keyword is used in method or function signature to declare an exception that the method may throw while execution of code
    throw keyword can be used to throw both checked and unchecked exceptions throws keyword can be used only with checked exceptions.
    throw is used within the method.throws is used within the method signature
    Syntax: throw new exception_class("error message");Syntax: void method() throws ArithmeticException
    We can throw only one exception at a timeWe can declare multiple exceptions using the throws keyword that the method can throw

Common Scenarios of Java Exceptions

1. ArithmeticException

This exception is raised by JVM when the programmer tries to perform any arithmetic operation that is not possible in mathematics. One of the frequently occurring arithmetic exceptions is when we divide any number with zero.


int a=30/0; //ArithmeticException  

2. NullPointerException

This occurs when a user tries to access a variable that stores null values. For example, if a variable stores a null value and the user tries to perform any operation on that variable throws NullPointerException.


String s=null;  
System.out.println(s.length());//NullPointerException

3. NumberFormatException

If the formatting of any variable or number is mismatched, it may result in NumberFormatException.


String s="ScholarHat";  
int i=Integer.parseInt(s);//NumberFormatException 

4. ArrayIndexOutOfBoundsException

When an array exceeds its size, the ArrayIndexOutOfBoundsException occurs.


int a[]=new int[6];  
a[10]=80; //ArrayIndexOutOfBoundsException

5. StringIndexOutOfBoundsException

It is the same as ArrayIndexOutOfBoundsException but it is for strings instead of arrays. Here if the length of a string is less than what we are trying to access there occurs the StringIndexOutOfBoundsException.


String s = "I am learning Java on ScholarHat.";
System.out.println("String length is:" + s.length());
System.out.println("Length of substring is:" + s1.substring(40)); //StringIndexOutOfBoundsException

Advantages of Exception Handling in Java

  • Program execution continues even if an exception is raised and handled, it does not lead to the termination abruptly.
  • With exception handling it is easy to identify errors that occurred while execution.
  • The exceptions thrown in a Java program are objects of a class. Since the Throwable class overrides the toString() method, you can obtain a description of an exception in the form of a string.
  • Java provides several superclasses and subclasses that group exceptions based on their type it is easy to differentiate and group exceptions.
Summary

This article covers exception handling in Java, including how to handle exception handling in Java. It also includes the various types of exception handling in Java with examples. If you're looking to learn Java, this article will provide you with insights into effectively managing exceptions in your code. Through this detailed exploration of exception handling in Java, learners undergoing Java Certification training can develop a solid understanding of this crucial topic and acquire the necessary skills to effectively handle exceptions in their Java programs.

FAQs

Q1. What is exception handling in Java?

To avoid crashes and allow for regulated error recovery, Java's exception-handling procedure deals with unforeseen or extraordinary occurrences that occur during program execution.

Q2. What are the 5 keywords in Java exception handling?

Try, Catch, Throw, Throws, and Finally are the five keywords used in Java exception handling.

Q3. What are the types of exceptions in Java?

Checked (compile-time checked) and unchecked(runtime) exceptions are the two categories used to classify Java exceptions.

Q4. What type of error is an exception?

In Java, an exception is a technique for dealing with extraordinary runtime circumstances and is not regarded as a mistake.

Q5. What is a catch block in Java?

Specific Java exceptions are captured and handled in a catch block, enabling a controlled response to unusual events that take place inside a try block.

Share Article
Batches Schedule
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this