Learn Java Easy. Chapter 12 Exercises

Chapter 12 Exercises – Try & Catch in Java

Chapter 12 Exercises

Exercise 1. Division by zero. Write a program that asks the user for two numbers and tries to divide the first by the second. Handle the ArithmeticException in case of division by zero.

Solution:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter the first number:");
        int num1 = scanner.nextInt();

        System.out.println("Enter the second number:");
        int num2 = scanner.nextInt();

        try {
            int result = num1 / num2;
            System.out.println("The result is: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Cannot divide by zero.");
        }

        scanner.close();
    }
}

Exercise 2. Handling NumberFormatException: Write a program that asks the user for an integer and tries to convert it. Handle the NumberFormatException in case the format is invalid. Once you’ve completed the exercise, try inserting a decimal number to see what happens.

Solution:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter an integer:");
        String input = scanner.nextLine();

        try {
            int number = Integer.parseInt(input);
            System.out.println("The entered number is: " + number);
        } catch (NumberFormatException e) {
            System.out.println("Error: Invalid number format.");
        }

        scanner.close();
    }
}

Exercise 3. Index out of range in an array. Write a program that creates an array of 5 elements and tries to access a position out of range. Handle the ArrayIndexOutOfBoundsException

Solution:

public class Main {

    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};

        try {
            int value = array[10];
            System.out.println("The value is: " + value);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: Index out of range.");
        }
    }
}

Exercise 4. Invalid arithmetic operation. Write a program that asks the user for two numbers and subtracts them. Handle the ArithmeticException if the operation is invalid for some reason (e.g., subtraction of extremely large values).

Solution:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter the first number:");
        long num1 = scanner.nextLong();

        System.out.println("Enter the second number:");
        long num2 = scanner.nextLong();

        try {
            long result = Math.subtractExact(num1, num2);
            System.out.println("The result is: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Invalid arithmetic operation.");
        }

        scanner.close();
    }
}

Exercise 5. String concatenation. Write a program that tries to concatenate a very large number of strings, causing an OutOfMemoryError. Handle the exception.

Solution:

public class Main {

    public static void main(String[] args) {
        try {
            String str = "";

            for (int i = 0; i < Integer.MAX_VALUE; i++) {
                str += "a";
            }

        } catch (OutOfMemoryError e) {
            System.out.println("Error: Insufficient memory for the operation.");
        }
    }
}

Did you like it? Don’t keep it to yourself — share it like juicy gossip! 😏