1.

Write a program in Java to show a basic “divide by 0 exception”.

Answer»

Divide by zero exception occurs when we try to divide a number by 0 in Java. Following is the program showing divide by 0 exception.

import java.util.*;
class Main {
public static void main(String args[]) {
// Your code goes here
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
System.out.println("Dividing this number by 0");
try {
System.out.println(n/0);
} catch(Exception e) {
System.out.println(e);
}
System.out.println("Program completed");
}
}

Output

Input: 3

Output:
Dividing this number by 0
java.lang.ArithmeticException: / by zero
Program completed

Important: In this question, we used the try and catch block for handling the divide by 0 exception. Hence, the complete execution of the program took place. Otherwise, the program would have stopped at the exception, and “Program completed” would not have been printed.




Discussion

No Comment Found