types of exception in java

ht‮w//:spt‬ww.lautturi.com
types of exception in java

In Java, there are several types of exceptions that can be thrown during the execution of a program.

  1. Checked exceptions: These are exceptions that are checked at compile-time and must be caught or declared in a throws clause. Checked exceptions include exceptions that are defined in the java.lang and java.io packages, such as IOException and SQLException.

  2. Unchecked exceptions: These are exceptions that are not checked at compile-time and do not need to be caught or declared in a throws clause. Unchecked exceptions include runtime exceptions and errors, such as NullPointerException and OutOfMemoryError.

  3. Errors: These are serious exceptions that indicate a problem with the system and are generally not recoverable. Examples of errors include StackOverflowError and VirtualMachineError.

  4. Custom exceptions: In addition to the built-in exception classes, you can also create custom exception classes in your Java code. Custom exceptions can be checked or unchecked, depending on whether they extend Exception or RuntimeException.

Here is an example of how to create and throw a custom checked exception in Java:

import java.io.IOException;

class CustomException extends IOException {
  public CustomException(String message) {
    super(message);
  }
}

public class Example {
  public static void main(String[] args) throws CustomException {
    throw new CustomException("An error occurred");
  }
}

In this example, the CustomException class extends IOException, which is a checked exception. Therefore, the CustomException class is also a checked exception and must be caught or declared in a throws clause.

Created Time:2017-10-17 22:51:24  Author:lautturi