Why we need Custom Exception
Exceptions are technical causes which should be wrapped in a presentable way with a specific business logic and workflow. adding a higher abstraction layer for the exception handling, which results in more meaningful and readable API
How to write Custom Exception
All you need to do is create a new class and have it extend Exception. If you want an Exception that is unchecked, you need to extend RuntimeException.
Note: A checked Exception is one that requires you to either surround the Exception in a try/catch block or have a ‘throws’ clause on the method declaration. (like IOException) Unchecked Exceptions may be thrown just like checked Exceptions, but you aren’t required to explicitly handle them in any way (IndexOutOfBoundsException).
Exception, if you want your exception to be checked (i.e: required in a throws clause).RuntimeException, if you want your exception to be unchecked.
Creating Custom Checked Exception
Note:constructor takes a Throwable’s subclass which is the origin (cause) of the current exception
public class StudentStoreException extends Exception { public StudentStoreException(String message, Throwable cause) { super(message, cause); } }
Creating Custom Unchecked Exception
public class IncorrectFileExtensionException extends RuntimeException { public IncorrectFileExtensionException(String errorMessage, Throwable err) { super(errorMessage, err); } }
Methods in Custom Exception
public class MyOwnException extends Exception { public MyOwnException() { } public MyOwnException(String message) { super(message); } public MyOwnException(Throwable cause) { super(cause); } public MyOwnException(String message, Throwable cause) { super(message, cause); } }