How can I write custom Exceptions?

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).

For example:

public class MyNewException extends RuntimeException {

    public MyNewException(){
        super();
    }

    public MyNewException(String message){
        super(message);
    }
}

Leave a Comment