Java Program to Handle Divide by Zero and Multiple Exceptions


Exceptions are the unusual events which disrupt the normal flow of execution of a program. When an exception occurs an object called exception object is generated, which contains details of exception like name,description,state of program. In this section, we are going to write a java program to handle divide by zero exception and how to handle multiple exceptions.

Types of Exceptions−

There are three types of exceptions −

  • Checked exception − Checked exceptions are compile time exceptions i.e, they are checked during compilation of program.These cannot be ignored and must be handled by the programmer.

Examples − IOException,SQLException, ClassNotFounException.

  • Unchecked exception − Unchecked exceptions are runtime exceptions i.e, they are ignored during compilation and checked during execution of a program.

Examples −NullPointerExceptions,ArthemeticException and ArrayIndexOutOfBoundException

  • Errors − Errors are the exceptions that cannot be recoverable and usually occur due to problems in the Java Virtual Machine or system resources. Errors are different from exceptions, errors should not be caught or handled by the programmer, as they indicate us that a severe problem is present and that cannot be fixed by the program.

Examples − OutOfMemoryError, StackOverflowError.

Examples of different types of exceptions in Java

  • ArithmeticException − Thrown when there is an issue with arithmetic operation which produces an overflow or underflow, or when dividing by zero.

  • NullPointerException − Thrown when we are pointing to a null object.

  • ArrayIndexOutOfBoundsException − Thrown when we try to access an index which is out of bounds.

  • IOException − Thrown when an input/output operation fails.

  • FileNotFoundException − Thrown when trying to access a file that does not exist.

Exception Handling

Exception handling is a process of handling the exceptions raised during the execution of a program so that the flow of execution will not be disrupted. This is done using try-catch block in Java. Try block contains the code which may throw an exception and catch block contains code which handles the exception.

We can either use in-built exceptions or create a custom or user-defined exception. Custom Exception extends either Exception class or RuntimeException class.

Syntax

try-catch Block − try - catch block in java is used to handle exceptions. The try - block contains the code which may throw an exception. The catch block catches the exception and handles the exception.

try {
   // Protected code
} catch (ExceptionName e1) {
   // Catch block
}

getMessage() − This method is used to get a detailed description of the exception as a string.

exceptionObject.getMessage()

throw − throw is a keyword in Java used to explicitly throw an exception.

super() − super() method is used to called a method from parent class.

We will now discuss different approaches in Java to handle Divide by Zero Exception by implementing java code.

Approach 1: Using try-catch block

In this approach, we use try-catch block in java to handle divide by zero exception. Steps we follow in this approach are as follows −

  • We initialize two numbers for numerator and denominator. We initialize denominator with zero.

  • In try block we write the division statement as it may throw an exception and in catch block we handle the exception using arithmetic exception.

Now, let us look into an example of implementing code in java.

Example

In this example, We initialize two variables ‘numerator’ and ‘denominator’, we make sure that we initialize denominator with zero and we perform division operation, as we can’t perform division using zero, an exception is throwed and it is caught using catch block

//Java program to handle divide by zero exception
import java.util.*;
public class Main{
   public static void main(String[] args) {
      
      int numerator  = 7;
      int denominator = 0;
      try {
         int answer = numerator / denominator;
         System.out.println("Result: " + answer);
      } catch (ArithmeticException ex) {
         System.out.println("Error: " + ex.getMessage());
         System.out.println("Cannot divide a value by zero.");
      }
   }
}

Output

Error: / by zero
Cannot divide a value by zero.

Approach 2: Using custom exception class

In this approach, we will implement a custom class or a class created by a programmer to handle divide by exception in java. Steps we follow in this approach are as follows −

  • We initialize two numbers for numerator and denominator. Denominator value is initialised with zero.

  • We create a custom class for divide by zero exception which extends exception class

  • In try block we explicitly throw the exception and call custom class using catch block to handle the exception.

Example

In this example, we created a ‘DivideByZeroException’ custom class and extends ‘Exception’. This class handles the exception caused by dividing by zero. When an exception is caused in main method we call the custom class using ‘throw’ keyword by creating an object to the class using ‘new; keyword.

import java.util.*;
class DivideByZeroException extends Exception {
   public DivideByZeroException(String message) {
      super(message);
   }
}
public class Main {
   public static void main(String[] args) {
      int numerator = 5;
      int denominator = 0;
      try {
         if (denominator == 0) {
            throw new DivideByZeroException("Error: Cannot divide a number by zero.");
         }
         int answer  = numerator / denominator;
         System.out.println("Result: " + answer);
      } catch (DivideByZeroException ex) {
         System.out.println(ex.getMessage());
      }
   }
}

Output

Error: Cannot divide a number by zero.

Handling Multiple Exceptions

Handling Multiple exceptions is nothing but having multiple catch blocks for a single try block and handling multiple exceptions occurring in code present in try block. We will handle catch different kind of exceptions and handle them using each catch block.

In this approach, we will handle the exceptions occurred in a single try and use multiple catch blocks for multiple exception handling.

Steps

  • Declare a try block and Initialize two integer variables namely numerator and denominator. denominator variable is initialized with 0.

  • Now, throw an ArithmeticException if denominator value is equal to zero.

  • Write multiple catch blocks to handle different exceptions.

  • Use different in-built methods in java and print the exception messages and exceptions that occurred.

Example

In this example, we use a single try block followed by multiple catch blocks. If the ArithmeticException is thrown from try block, then the catch block handling the ArithmeticException code is executed. If the try block throws a NullPointerException then that particular catch block is executed. If the catch block doesn’t handle the specific exception thrown by try block then the last catch block code is executed as it is handling the generic Exception case. From, the example as the denominator value initialized is zero we throw an ArthemicException use ‘throw’ keyword and the catch block handling the ArthemeticException is been executed.

import java.util.*;
public class Main {
   public static void main(String[] args) {
      try {
         int numerator = 10, denominator = 0 ;
         if(denominator == 0) {
            throw new ArithmeticException();
         }
      } catch (ArithmeticException e) {
         System.out.println("ArithmeticException caught.");
         System.out.println("Message: " + e.getMessage());
         System.out.println("Stack Trace: ");
         e.printStackTrace();
         System.out.println("Cause: " + e.getCause());
      } catch (NullPointerException e) {
         System.out.println("NullPointerException caught.");
         System.out.println("Message: " + e.getMessage());
         System.out.println("Stack Trace: ");
         e.printStackTrace();
         System.out.println("Cause: " + e.getCause());
      } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("ArrayIndexOutOfBoundsException caught.");
         System.out.println("Message: " + e.getMessage());
         System.out.println("Stack Trace: ");
         e.printStackTrace();
         System.out.println("Cause: " + e.getCause());
      } catch (Exception e) {
         System.out.println("NullPointerException caught.");
         System.out.println("Message: " + e.getMessage());
         System.out.println("Stack Trace: ");
         e.printStackTrace();
         System.out.println("Cause: " + e.getCause());
      }
   }
}

Output

ArithmeticException caught.
Message: null
Stack Trace: 
Cause: null
java.lang.ArithmeticException
	at Main.main(Main.java:7)

Thus, in this article we have discussed how to handle exception caused by dividing with zero and how to handle multiple exceptions in java using different approaches.

Updated on: 11-Apr-2023

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements