OOPS

Assignment - 10

Objective

Write a program to demonstrate the use of only try & catch keywords.

Programming Language & Compilation

$ javac Program.java
$ java Program

Source Code

import java.lang.System;

// Minimal example to show use of `try` & `catch` keyword.
public class Program {

  public static void main(String[] args) {
    // catch block is not invoked.
    try {
      int a = 10, b = 2;
      double result = divide(a, b);
      System.out.println(a + " / " + b + " = " + result);
    } catch (ArithmeticException e) {
      System.out.println("Division by zero.");
    }
    // catch block is invoked.
    try {
      int a = 69, b = 0;
      double result = divide(a, b);
      System.out.println(a + " / " + b + " = " + result);
    } catch (ArithmeticException e) {
      System.out.println("Division by zero.");
    }
  }

  private static int divide(int x, int y) {
    return x / y;
  }
}

Output

right-click & select “Open image in new tab” for larger image.

WindowsTerminal_2cIL19QsF7