try catch block in java with example

try catch block in java with example

Certainly! In Java, the try-catch block is used to handle exceptions. The try block contains the code that might throw an exception, and the catch block catches and handles the exception if it occurs. Here’s an example to demonstrate the usage of the try-catch block:

Example:

Example

import java.util.Scanner;
/*
 * Author: Zameer Ali Mohil
 * */
public class ExceptionHandlingExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        try {
            int num = scanner.nextInt(); // This might cause an InputMismatchException
            int result = 10 / num; // This might cause an ArithmeticException if num is 0
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            // Handle ArithmeticException (division by zero)
            System.out.println("Error: Division by zero is not allowed.");
        } catch (java.util.InputMismatchException e) {
            // Handle InputMismatchException (non-integer input)
            System.out.println("Error: Please enter a valid integer.");
        } finally {
            // Cleanup operations (closing resources, etc.) can go here
            scanner.close();
        }
    }
}

In this example:

  • The try block contains the code that might throw exceptions (an InputMismatchException if a non-integer input is given and an ArithmeticException if the user inputs 0).
  • The catch blocks handle specific exceptions. In this case, the program catches ArithmeticException and InputMismatchException separately and provides specific error messages for each type of exception.
  • The finally block is optional and is used for cleanup operations. In this example, it closes the Scanner object, ensuring that it is always closed, regardless of whether an exception occurred or not.

This try-catch block structure allows the program to gracefully handle exceptions and provide meaningful error messages to the user, enhancing the user experience and preventing the program from crashing due to unexpected inputs.

Leave a Reply

Your email address will not be published. Required fields are marked *