Java Program to demonstrate simple try ... catch .
Objective
Write a Java program to demonstrate a simple try-catch block for handling division by zero.
Algorithm / Approach
- Create a method
divide(int a, int b)that dividesabyband prints the result. - In main, read two integers from the user.
- Wrap the call to
t.divide(x, y)inside atry { ... }block. - Immediately follow it with a
catch (ArithmeticException e) { ... }block. - Inside the catch block, print a custom error message like "Can't Divide By 0".
Test.java
import java.util.Scanner;
class Test {
void divide(int a, int b) {
int c = a/b;
System.out.println("Result = "+c);
}
}
class Main {
public static void main(String[] a)
{
Test t = new Test();
Scanner s=new Scanner(System.in);
System.out.print("Enter Num1: ");
int x = s.nextInt();
System.out.print("Enter Num2: ");
int y = s.nextInt();
try{
t.divide(x,y);
}
catch(ArithmeticException e) {
System.out.print("Can't Divide By 0");
}
}
}
Expected Output
Enter Num1: 5 Enter Num2: 0 Can't Divide By 0
Explanation of the Program
- An exception is an unwanted or unexpected event that disrupts the normal flow of a program.
- If a user enters 0 for the second number, the JVM will throw an
ArithmeticExceptionbecause division by zero is mathematically undefined in integer arithmetic. - Without the try-catch block, the program would crash instantly. By wrapping the risky code in a
tryblock, we can gracefully "catch" the error and keep the program running.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)