Skip to main content

Command Palette

Search for a command to run...

Lab Sheet 9: Exception Handling in Java

Published
3 min read
Lab Sheet 9: Exception Handling in Java
A
I co-founded🫆digizen (fighting internet chaos 🧠), building an AI app to tackle misinformation, and running ideaGeek to turn “I have an idea” into real startups. I also share tech + travel on YouTube (TechNomad & Rz Omar). I touch grass too 🌱… but mostly to debug life 💻

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.

More from this blog

T

TechNomad

46 posts

TechNomad is mostly coding exercises, not long boring explanations 😌. I share what I teach and learn through hands-on problems—mainly for my students, but anyone can jump in. If you learn by doing (and breaking things), you’ll fit right in. Less theory, more “try this and see what happens.”