Show List

Exception Handling

Exception handling in Java is a mechanism for handling errors that occur during the execution of a program. The purpose of exception handling is to allow the program to continue running even in the presence of errors.

Exceptions in Java are objects that represent errors and are thrown by the Java runtime system. When an error occurs, the Java runtime system generates an exception and throws it to be caught and handled by the program. For example:

try {
   int a = 5 / 0;
} catch (ArithmeticException e) {
   System.out.println("An arithmetic exception has occurred: " + e.getMessage());
}

In this example, a division by zero error occurs and the Java runtime system generates an ArithmeticException. The exception is caught by the catch block, which prints a message indicating that an arithmetic exception has occurred.

You can also define your own custom exceptions by creating a new class that extends the Exception class. For example:

class InvalidInputException extends Exception {
   public InvalidInputException(String message) {
      super(message);
   }
}

try {
   if (input.equals("")) {
      throw new InvalidInputException("Input cannot be empty.");
   }
} catch (InvalidInputException e) {
   System.out.println("An invalid input exception has occurred: " + e.getMessage());
}

In this example, a custom exception, InvalidInputException, is defined. The exception is thrown in the try block if the input is empty and is caught by the catch block, which prints a message indicating that an invalid input exception has occurred.

Exception handling is a powerful mechanism for preventing errors from disrupting the normal flow of a program. By handling exceptions, you can provide more robust and error-resistant programs.


    Leave a Comment


  • captcha text