Lab Sheet 9: Exception Handling in Java

Arzath AreeffArzath Areeff
3 min read

Exercise 1: Identifying and Handling Syntax Errors

Task:

  1. Write a Java program with intentional syntax errors (e.g., missing semicolons, incorrect variable names).

  2. Compile the program and observe the compiler errors.

  3. Correct the errors and recompile.

Sample Code (with errors):

public class SyntaxErrorDemo {
    public static void main(String args[]) {
        int x = 10
        System.out.println("Value of x is " + x)
    }
}

Expected Output:

  • Compile-time errors before correction.

  • Correct output after fixing errors.


Exercise 2: Handling Runtime Exceptions

Task:

  1. Write a program that performs division (a / b).

  2. Allow the user to input values for a and b.

  3. Handle the ArithmeticException (division by zero) using a try-catch block.

Sample Code:

import java.util.Scanner;

public class DivisionDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter two numbers: ");
        int a = sc.nextInt();
        int b = sc.nextInt();

        try {
            System.out.println("Result: " + (a / b));
        } catch (ArithmeticException e) {
            System.out.println("Error: Division by zero!");
        }
    }
}

Expected Output:

  • If b = 0, the program should catch the exception and display an error message.

  • Otherwise, it should print the division result.


Exercise 3: Multiple Catch Blocks

Task:

  1. Write a program that reads an array element at a given index.

  2. Handle both ArrayIndexOutOfBoundsException and NumberFormatException (if input is not a number).

Sample Code:

import java.util.Scanner;

public class ArrayExceptionDemo {
    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40, 50};
        Scanner sc = new Scanner(System.in);

        try {
            System.out.print("Enter index: ");
            int index = Integer.parseInt(sc.nextLine());
            System.out.println("Element at index " + index + ": " + arr[index]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: Invalid index!");
        } catch (NumberFormatException e) {
            System.out.println("Error: Please enter a valid number!");
        }
    }
}

Expected Output:

  • If the index is out of bounds, display an error.

  • If the input is not a number, display a different error.


Exercise 4: Using Finally Block

Task:

  1. Write a program that reads a file.

  2. Handle FileNotFoundException if the file does not exist.

  3. Use a finally block to ensure a message is printed regardless of whether an exception occurs.

Sample Code:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileReadDemo {
    public static void main(String[] args) {
        Scanner sc = null;
        try {
            sc = new Scanner(new File("test.txt"));
            while (sc.hasNextLine()) {
                System.out.println(sc.nextLine());
            }
        } catch (FileNotFoundException e) {
            System.out.println("Error: File not found!");
        } finally {
            if (sc != null) {
                sc.close();
            }
            System.out.println("File read operation completed.");
        }
    }
}

Expected Output:

  • If the file exists, display its contents.

  • If not, display an error but still print the finally block message.

0
Subscribe to my newsletter

Read articles from Arzath Areeff directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Arzath Areeff
Arzath Areeff

I co-founded digizen.lk to promote online safety and critical thinking. Currently, I’m developing an AI app to fight misinformation. As Founder and CEO of ideaGeek.net, I help turn startup dreams into reality, and I share tech insights and travel stories on my YouTube channels, TechNomad and Rz Omar.