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.
Syntaxpublic class MyCustomException extends RuntimeException { public MyCustomException(String message) { super(message); } }
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.
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); } }
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!