Home > Java > javaTutorial > body text

How to create custom unchecked exception in Java?

WBOY
Release: 2023-09-11 16:37:02
forward
1210 people have browsed it

How to create custom unchecked exception in Java?

We can create custom unchecked Exception by extending RuntimeException in Java.

UncheckedExceptionInherits from the Error class or the RuntimeException class. Many programmers believe that we cannot handle these exceptions in our programs because they represent types of errors that cannot be recovered from while the program is running. When an unchecked exception is thrown, it is usually caused by abusing code , passing null or other incorrect arguments.

Syntax
public class MyCustomException extends RuntimeException {
   public MyCustomException(String message) {
      super(message);
   }
}
Copy after login

Implementing unchecked exceptions

The implementation of custom unchecked exceptions is almost similar to checked exceptions in Java. The only difference is that unchecked exceptions must extend RuntimeException instead of Exception.

Example

public class CustomUncheckedException extends RuntimeException {
   /*
   * Required when we want to add a custom message when throwing the exception
   * as throw new CustomUncheckedException(" Custom Unchecked Exception ");
   */
   public CustomUncheckedException(String message) {
      // calling super invokes the constructors of all super classes
      // which helps to create the complete stacktrace.
      super(message);
   }
   /*
   * Required when we want to wrap the exception generated inside the catch block and rethrow it
   * as catch(ArrayIndexOutOfBoundsException e) {
      * throw new CustomUncheckedException(e);
   * }
   */
   public CustomUncheckedException(Throwable cause) {
      // call appropriate parent constructor
      super(cause);
   }
   /*
   * Required when we want both the above
   * as catch(ArrayIndexOutOfBoundsException e) {
      * throw new CustomUncheckedException(e, "File not found");
   * }
   */
   public CustomUncheckedException(String message, Throwable throwable) {
      // call appropriate parent constructor
      super(message, throwable);
   }
}
Copy after login

The above is the detailed content of How to create custom unchecked exception in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!