tags:

views:

341

answers:

5

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

+18  A: 

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);
    }
}
jjnguy
Note: if you are using Eclipse, simply write 'throw new <CustomName>Exception', and then use the Autofix (Ctrl+1). This will create a new class for you which extends Exception, and contains the boilerplate code.
James Van Huis
+6  A: 

just extend either

  • Exception, if you want your exception to be checked (ie: required in a throws clause)
  • RuntimeException, if you want your exception to be unchecked.
toolkit
+1 for distinguishing between checked and unchecked.
ojrac
I did too ...
jjnguy
A: 

Look Here

LB
+1  A: 

Take a look at:

http://www.onjava.com/pub/a/onjava/2003/11/19/exceptions.html?page=1

An example is given there on page 2:

public class DuplicateUsernameException
    extends Exception {
    public DuplicateUsernameException 
        (String username){....}
    public String requestedUsername(){...}
    public String[] availableNames(){...}
}

along with a set of guidelines for when and why you'd create your own exceptions.

Jon
A: 

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

Jim Ferrans