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 1:

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

Solution 2:

just extend either

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

Solution 3:

Be sure not to go overboard with exceptions, especially checked exceptions. I'd recommend reading Chapter 9 of Joshua Bloch's Effective Java, and in particular his Item 60 (Favor the use of standard exceptions). His recommendations also include using checked exceptions for exceptions that can be recovered from, using unchecked exceptions (RuntimeExceptions) for programming errors, and avoiding the unnecessary use of checked exceptions.

If an InvalidBankAccount exception is thrown whenever an programming error is found, you probably just want to throw a standard unchecked Java IllegalStateException instead. (This neatly sidesteps the need to declare serialVersionUID.)