Exception handling in Java

11 Feb 2023
Intermediate
124 Views

Exception handling in Java

What is Exception handling in Java?

Exception handling in Java is an unwanted event that happens during the execution of the program. It terminates the program by affecting the flow of the program. There are various reasons that are caused exception handling in Java, such as:

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

Types of Exceptions in Java

There are two 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

Runtime Exception or unchecked exception in Java

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

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

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

Errors in java

Errors in java are important parts of the programming language. They are used to indicate that something has gone wrong during the program’s execution and communication of this is essential for debugging. Error exceptions allow for specific errors to be identified since they are unique and can include a description of the problem. Error exceptions also provide some structure on how to handle them so developers don't have to completely start from scratch. Whenever an error occurs, it's caught using this keyword - allowing developers to quickly place corrective action. Error Exceptions may be caused due to various reasons such as memory leaks, poor data input validation, or server problems but regardless of the cause, Errors in java programming language play an important role in software development by providing real-time debugging capabilities. Errors in java help prevent disastrous mistakes when code is tested and makes it easier to find any potential issues before the program is released.

Exception Hierarchy in Java

Exception hierarchy in Java can be defined by this picture:

Java Exception Handling Approaches

In Java, there are different types of approaches to exception handling those are

  • Try..catch block
  • Finally block
  • Throw and throws keywords

Try..catch block in Java

Try.. catch block is generally used in Java for doing exception handling. Here, in Java, a code might generate an exception in the "try" block. All the "try" blocks here are followed by "catch" blocks for catching the exception.

Syntax


try
  {
    // code
  }
  catch(Exception e)
  {
    // code
  }

Example


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

Output


ArithmeticException => / by zero

Finally block in Java

Finally block in Java always execute even if there are no exceptions. This is an optional block. 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


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");
      }
    }
  }

Output


ArithmeticException => / by zero

This is the finally block

Throw and throws keywords in Java

Throw keyword in Java is used for explicitly throwing a single exception. When an exception is ready to throw then the program moves to try block to catch block

Example


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

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)

Summary

This article covers exception handling in Java with examples including how to handle exception handling in Java. It also includes the various types of exception handling in Java with examples.

Accept cookies & close this