Basic exception handling

In this exercise, you will learn exception handling in Java, a fundamental technique for handling errors and preventing programs from stopping unexpectedly. Discover how to use the try, catch, and finally constructs to efficiently catch and handle exceptions. Through hands-on exercises, you will improve the stability and reliability of your Java applications.

Topic

Control Structures

Java Exercise

In this exercise, you will create a Java program that implements exception handling using try, catch, and finally. You will learn how to handle runtime errors, preventing the program from stopping unexpectedly.

Instructions:

  1. Prompt the user to enter two integers.
  2. Perform division between the two numbers.
  3. Use a try-catch block to handle exceptions if the divisor is zero.
  4. In the catch block, display an error message if division by zero occurs.
  5. Use a finally block to display a message indicating that execution has completed.
  6. Compile and run the program to verify that it works correctly.

This exercise will help you understand how to handle exceptions in Java to make your programs more robust and resistant to unexpected errors.


import java.util.Scanner;

public class ExceptionHandling {
    public static void main(String[] args) {
        // Create a Scanner object for user input
        Scanner scanner = new Scanner(System.in);
        
        try {
            // Ask the user to enter two numbers
            System.out.print("Enter the numerator: ");
            int numerator = scanner.nextInt();
            
            System.out.print("Enter the denominator: ");
            int denominator = scanner.nextInt();
            
            // Perform the division and display the result
            int result = numerator / denominator;
            System.out.println("Result: " + result);
            
        } catch (ArithmeticException e) {
            // Catch and handle the exception if the denominator is 0
            System.out.println("Error: Cannot divide by zero.");
            
        } finally {
            // Message that always executes
            System.out.println("Execution finished.");
        }
        
        // Close the Scanner
        scanner.close();
    }
}

 Output:

Enter the numerator: 10
Enter the denominator: 2
Result: 5
Execution complete.

 Output with Exception:

Enter numerator: 10
Enter denominator: 0
Error: Cannot divide by zero.
Execution terminated.

This program demonstrates how to handle exceptions in Java using try-catch to prevent errors when dividing by zero, and finally to execute closing code regardless of whether an exception occurs.


 Share this JAVA exercise