Search code examples
javaexception

How can I write custom Exceptions?


How can I create a new Exception different from the pre-made types?

public class InvalidBankFeeAmountException extends Exception{
    public InvalidBankFeeAmountException(String message){
        super(message);
    }
 }

It will show the warning for the InvalidBankFeeAmountException which is written in the first line.


Solution

  • 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);
        }
    }