What is meant by exceptions? How an exception in exception is your own sample code?


Q.) What is meant by exceptions? How an exception in exception is your own sample code?

Subject: Object Oriented Programming and Methodology

Exceptions: in exception during program execution that disrupt the normal flow of the program. It occurs when the program encounters an unexpected condition that it cannot handle. The program must handle the exception to prevent it from causing a program crash.

Types of exception:

  1. Compile-time exceptions: These are detected by the compiler before the program is executed.
    • Example: Syntax errors, type errors, etc.
  2. Runtime exceptions: These are detected during the program execution.
    • Example: ArrayIndexOutOfBoundsException, ArithmeticException, NullPointerException, etc.

Exception Handling in Java:

  1. try block: This block contains the code that might throw an exception.
  2. catch block: This block contains the code that will handle the exception if it is thrown.
  3. finally block: This block contains the code that will always be executed, whether or not an exception is thrown.

Example:

try {
    int a = 10;
    int b = 0;
    int c = a / b; // ArithmeticException: division by zero
    System.out.println(c); // unreachable code
} catch (ArithmeticException e) {
    System.out.println("Division by zero is not allowed");
} finally {
    System.out.println("This block will always execute");
}

Custom Exception: You can also create your own custom exception by extending the Exception class and specify the functionality that you want to include in your exception.

For example:

public class CustomException extends Exception {

    public CustomException(String message) {
        super(message);
    }
}

public class Main {

    public static void main(String[] args) {
        try {
            throw new CustomException("This is a custom exception");
        } catch (CustomException e) {
            System.out.println(e.getMessage());
        }
    }
}

Output:

This is a custom exception

Benefits of Exception Handling:

  • Improves the robustness and reliability of the program.
  • Makes the code easier to debug and maintain.
  • Provides a way to handle unexpected conditions gracefully.

Conclusion: Exceptions are a critical part of error handling in programming. Proper exception handling allows you to handle errors gracefully, preventing program crashes, and improving the overall reliability of your software.