Java Exceptions

java

In Java, an exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Exceptions are typically thrown when an error or unexpected condition occurs, such as when a file cannot be found or when an array index is out of bounds.

To handle exceptions in Java, you can use a try-catch block. The try block contains the code that may throw an exception, and the catch block contains the code to handle the exception.

Here is an example of a try-catch block in Java:

try {
  // code that may throw an exception
} catch (ExceptionType1 e) {
  // code to handle ExceptionType1
} catch (ExceptionType2 e) {
  // code to handle ExceptionType2
}

You can specify multiple catch blocks to handle different types of exceptions.

To throw an exception in Java, you can use the throw statement:

if (x < 0) {
  throw new IllegalArgumentException("x cannot be negative");
}

In this example, an IllegalArgumentException is thrown if the value of x is negative.

You can also define your own custom exceptions by creating a class that extends java.lang.Exception or java.lang.RuntimeException.

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