Exception Handling in Java

Introduction to Exception handling in Java

Exception handling in Java is a mechanism to handle errors that occur during the execution of a program. It allows you to identify, handle, and recover from errors, so that your program can continue running.

There are two main types of exceptions in Java: checked and unchecked exceptions. Checked exceptions are those that must be explicitly handled by your program, while unchecked exceptions do not need to be handled explicitly.

To handle exceptions in Java, you can use the `try-catch` statement. The `try` block contains the code that you want to monitor for errors. If an error occurs, the program will jump to the nearest `catch` block that matches the type of exception that was thrown.

Here is an example of a `try-catch` statement:

try {
  // Code that may throw an exception
} catch (Exception e) {
  // Code to handle the exception
}

You can also use multiple `catch` blocks to handle different types of exceptions. For example, the following code handles two different types of exceptions:

try {
  // Code that may throw an exception
} catch (IOException e) {
  // Code to handle the IOException
} catch (SQLException e) {
  // Code to handle the SQLException
}
The `throw` keyword in exception handling in Java

The `throw` keyword in Java is used to explicitly throw an exception from a method or any block of code. Both checked and unchecked exceptions can be thrown using the `throw` keyword.

To throw an exception using the `throw` keyword, you simply need to create a new instance of the exception class and pass it to the `throw` keyword. For example, the following code throws an `ArithmeticException`:

throw new ArithmeticException("Division by zero");

You can also pass a custom message to the exception constructor. For example, the following code throws an `ArithmeticException` with a custom message:

throw new ArithmeticException("Division by zero is not allowed");

The `throw` keyword is a powerful tool for controlling the flow of your program and handling errors gracefully. However, it is important to use it carefully, as overuse of the `throw` keyword can make your code difficult to read and maintain.

Here are some tips for using the `throw` keyword effectively:

  • Only throw exceptions when it is absolutely necessary.
  • Be specific when throwing exceptions. Use the most specific exception class that matches the error that has occurred.
  • Provide a meaningful message with the exception. This will help you to track down and fix the error later.
  • Document the reasons for throwing exceptions in your code.

Here are some examples of when you might use the `throw` keyword:

  • To validate user input. For example, you might throw an `IllegalArgumentException` if a user enters an invalid value for a parameter.
  • To handle unexpected errors. For example, you might throw an `IOException` if you are unable to open a file.
  • To signal to the caller of a method that an error has occurred. For example, you might throw a `CheckedException` if a method is unable to complete its task successfully.

By using the `throw` keyword effectively, you can write more reliable and robust Java code.

The `throws` keyword in Java

The `throws` keyword in Java is used to declare that a method may throw a specific exception. This information can be used by the caller of the method to handle the exception appropriately.

To use the `throws` keyword, you simply need to list the exception types that the method may throw in the method signature. For example, the following method signature declares that the method may throw an `IOException`:

public void readFile(String filename) throws IOException {
}

This means that the caller of the `readFile()` method must handle the `IOException` exception, or declare that it throws the `IOException` exception to its caller.

The `throws` keyword is an important part of exception handling in Java. It allows you to communicate to the caller of a method the types of exceptions that the method may throw. This information can be used to write more robust and reliable code.

Here are some tips for using the `throws` keyword effectively:

  • Only declare exceptions in the `throws` clause that the method may actually throw.
  • Be specific when declaring exceptions. Use the most specific exception class that matches the error that may occur.
  • Document the reasons for declaring exceptions in your code.

Here are some examples of when you might use the `throws` keyword:

  • To declare that a method may throw an `IOException` when reading or writing to a file.
  • To declare that a method may throw a `SQLException` when connecting to or querying a database.
  • To declare that a method may throw a `NumberFormatException` when parsing a string as a number.

By using the `throws` keyword effectively, you can write more robust and reliable Java code.

The `finally` keyword in Java

The `finally` keyword in Java is used to execute a block of code after the corresponding `try` and `catch` blocks have been executed. The `finally` block is always executed, regardless of whether an exception is thrown or not.

The `finally` block is typically used to release resources, such as closing files or database connections. It can also be used to perform other cleanup tasks, such as logging errors or sending notifications.

Here is an example of a `try-catch-finally` block:

try {
  // Code that may throw an exception
} catch (Exception e) {
  // Code to handle the exception
} finally {
  // Code to release resources or perform other cleanup tasks
}

The `finally` block is executed even if an exception is thrown in the `try` block. This is because the `finally` block is executed after the `catch` block, even if the `catch` block is not executed.

The `finally` keyword is a powerful tool for ensuring that resources are always released and that cleanup tasks are always performed. It is important to use the `finally` keyword in any code that uses resources.

Here are some tips for using the `finally` keyword effectively:

  • Always use a `finally` block to release resources.
  • Use the `finally` block to perform other cleanup tasks, such as logging errors or sending notifications.
  • Ensure that the `finally` block is executed even if an exception is thrown.

Exception handling is an important part of writing reliable Java code. By handling exceptions properly, you can prevent your program from crashing and ensure that it can continue running even when errors occur.

Here are some tips for using exception handling effectively:

  • Use the `try-catch` statement to handle exceptions.
  • Be specific when handling exceptions. Use the most specific catch block that matches the type of exception you are expecting.
  • Handle all checked exceptions explicitly.
  • Log exceptions so that you can track them down and fix them later.
  • Document the reasons for using exception handling in your code.

Exercises

Code used for generating tyre pressure exception - Refer video for more information.


  package javaprogrammingdemo;
  public class javalabclass {
  
  public static void main(String[] args) {
    
    tyrePressureException oct7 = new tyrePressureException(35,24,35,35);
    oct7.check_pressure();
  }	
  }
  
  
  class tyrePressureException
  {
  private static final int fronttyres=35;
  private static final int reartyres=35;
  int frontyre1;
  int frontyre2;
  int reartyre1;
  int reartyre2;	
  
  public tyrePressureException(int frontyre1, int frontyre2, int reartyre1, int reartyre2) {
    this.frontyre1 = frontyre1;
    this.frontyre2 = frontyre2;
    this.reartyre1 = reartyre1;
    this.reartyre2 = reartyre2;
  }
  public void check_pressure()
  {
    if(frontyre1<fronttyres)
    {
      System.out.println("Alarm Front Tyre1 Pressure "+frontyre1);
    }
    if(frontyre2<fronttyres)
    {
      System.out.println("Alarm Front Tyre2 Pressure "+frontyre2);
    }
    if(reartyre1<reartyres)
    {
      System.out.println("Alarm Rear Tyre1 Pressure "+reartyre1);
    }
    if(reartyre2<reartyres)
    {
      System.out.println("Alarm Rear Tyre2 Pressure "+reartyre2);
    }
  }
  } 

Demo Code for throwing an Arithmetic Exception using throw keyword


  package javaprogrammingdemo;
  import java.util.Scanner;
  public class javalabclass {
  
    public static void main(String[] args) {
      
      try
      {
          //demo of an arithmetic exception	
          System.out.println("Enter the first number");
          Scanner sc = new Scanner(System.in);
          int firstnumber = sc.nextInt();
          System.out.println("Enter the second number");
          int secondnumber = sc.nextInt();
          if(secondnumber==2)
          {
            throw new satishException();
          }
          System.out.println(firstnumber/secondnumber);
      }
      catch(satishException e)
      {
        System.out.println("satishException is created");
      }
    }	
  }
  
  
  class satishException extends Exception
  {
      
  } 

Code for throwing an User Defined Exception with a custom message


  package javaprogrammingdemo;
  import java.util.Scanner;
  public class javalabclass {
  
  public static void main(String[] args) {
  
  try
  {
      //demo of an arithmetic exception	
      System.out.println("Enter the first number");
      Scanner sc = new Scanner(System.in);
      int firstnumber = sc.nextInt();
      System.out.println("Enter the second number");
      int secondnumber = sc.nextInt();
      if(secondnumber==2)
      {
        throw new satishException("satish exception was thrown by satish");
      }
      System.out.println(firstnumber/secondnumber);
  }
  catch(satishException e)
  {
    System.out.println(e.getMessage());
  }
  }	
  }
  
  class satishException extends Exception
  {
    public satishException(String s) {
      super(s);
    }
  } 

Code for demonstrating inheritance between user defined exceptions


  package javaprogrammingdemo;
import java.util.Scanner;
public class javalabclass {

  public static void main(String[] args) {
    
    try
    {
        //demo of an arithmetic exception	
        System.out.println("Enter the first number");
        Scanner sc = new Scanner(System.in);
        int firstnumber = sc.nextInt();
        System.out.println("Enter the second number");
        int secondnumber = sc.nextInt();
        if(secondnumber==2)
        {
          throw new satishException("satish exception was thrown by satish");
        }
        System.out.println(firstnumber/secondnumber);
    }
    catch(satishException e)
    {
      System.out.println(e.getMessage());
    }
  }	
}


class satishException extends Exception
{
  public satishException(String s) {
    super(s);
  }
}

class satish1exception extends satishException
{
  public satish1exception(String s) {
    super(s);
  }
}

class satish2exception extends satishException
{
  public satish2exception(String s) {
    super(s);
  }
} 

Code for demonstrating nested try catch.


  package javaprogrammingdemo;
  import java.util.*;
  public class javalabclass{
      public static void main(String args[]){
        
        //nested try and catch 
        try
        {
          System.out.println(23/0);
          try 
          {
            String satish=null;
            System.out.println(satish.length());
          }
          catch(NullPointerException k)
          {
            System.out.println("Null pointer exception handled here");
          }
        }
        catch(ArithmeticException e)
        {
          System.out.println("Arithmetic exception from outer try block");
        }
        System.out.println("Thanks for using our software");
      }
  } 

Code for demonstrating try catch with finally block.


  package javaprogrammingdemo;
  import java.util.*;
  public class javalabclass{
      public static void main(String args[]){
        
        try
        {
          System.out.println(23/0);
        }
        catch(Exception e)
        {
          System.out.println("Arithmetic exception handled here");
        }
        finally
        {
          System.out.println("Close all connections");
        }
        
      }
  } 

Code for demonstrating nested try with only a finally block.


  package javaprogrammingdemo;
  import java.util.*;
  public class javalabclass{
      public static void main(String args[]){
        
        //nested try and catch 
        try
        {
          //System.out.println(23/0);
          try 
          {
            String satish=null;
            System.out.println(satish.length());
          }
          finally
          {
            System.out.println("Closing the resources here");
          }
        }
        catch(NullPointerException e)
        {
          System.out.println("null pointer exception handled here");
        }
        catch(ArithmeticException e)
        {
          System.out.println("Arithmetic exception from outer try block");
        }
        System.out.println("Thanks for using our software");
      }
  } 

Code for demonstrating nested try and catch block with an user defined exception.


  package javaprogrammingdemo;
import java.util.Scanner;
public class javalabclass {

  public static void main(String[] args) {
    
    try
    {
        //demo of an arithmetic exception	
        System.out.println("Enter the first number");
        Scanner sc = new Scanner(System.in);
        int firstnumber = sc.nextInt();
        try
        {
          if(firstnumber==1)
          {
            throw new ArithmeticException();
          }
        }
        catch(ArithmeticException e)
        {
          System.out.println("First number cant be one");
        }
        System.out.println("Enter the second number");
        int secondnumber = sc.nextInt();
        if(secondnumber==2)
        {
          throw new satishException("satish exception was thrown by satish");
        }
        System.out.println(firstnumber/secondnumber);
    }
    catch(satishException e)
    {
      System.out.println(e.getMessage());
    }
  }	
}

class satishException extends Exception
{
  public satishException(String s) {
    super(s);
  }
}