Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to demonstrate simple try ... catch .

Java Code Example — Exception Handling Programs

ADVERTISEMENT

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

  1. Create a method divide(int a, int b) that divides a by b and prints the result.
  2. In main, read two integers from the user.
  3. Wrap the call to t.divide(x, y) inside a try { ... } block.
  4. Immediately follow it with a catch (ArithmeticException e) { ... } block.
  5. 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 ArithmeticException because 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 try block, we can gracefully "catch" the error and keep the program running.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT