53

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.

Ashish Ratan
  • 2,838
  • 1
  • 24
  • 50
Johanna
  • 27,036
  • 42
  • 89
  • 117
  • I created one Exception by myself which is shown above.create a class with the name of that special exception and extends Exception. BUT it has warning which is:The serializable class Exception does not declare a static final serialVersionUID field of long. How can I solve it????? – Johanna Jul 01 '09 at 19:57
  • 1
    You don't have to worry about that warning if you don't want to. Because the Exception class is serializable it requires you to set a serial id for the class. But, since it is just a warning, I usually ignore it. – jjnguy Jul 01 '09 at 20:01
  • but when I use this class as a type in the main() method the other warning will be shown that:Can not throw the type InvalidBankFeeAmountException. – Johanna Jul 01 '09 at 20:03
  • 1
    Did you declare it as "throws InvalidBankFeeAmountException"? – Michael Myers Jul 01 '09 at 20:27
  • The error you are getting leads me to believe that you are not correctly extending Exception. – jjnguy Jul 01 '09 at 20:33

5 Answers5

117

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
  • 136,852
  • 53
  • 295
  • 323
  • 40
    Note: if you are using Eclipse, simply write 'throw new 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 Jul 01 '09 at 18:23
  • 5
    I've heard it can be bad practice to extend [RuntimeExceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html): *If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.* – AncientSwordRage Apr 03 '13 at 11:46
  • I just read the rest of the answer, you've got it covered, I just need to read more than the code before commenting. – AncientSwordRage Apr 03 '13 at 11:50
  • 5
    @Pureferret I don't think it's bad practice to extend `RuntimeException`. It definitely makes your code easier to use if there aren't checked exceptions all over the place. – jjnguy Apr 03 '13 at 14:46
33

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.
Oleg Estekhin
  • 8,063
  • 5
  • 49
  • 52
toolkit
  • 49,809
  • 17
  • 109
  • 135
6

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

Jim Ferrans
  • 30,582
  • 12
  • 56
  • 83
3

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.

Jonathan Holloway
  • 62,090
  • 32
  • 125
  • 150
0
import java.util.Scanner;
class NotProperNameException extends Exception {
   NotProperNameException(String msg){
      super(msg);
   }
}
public class CustomCheckedException{
   private String name;
   private int age;
   public static boolean containsAlphabet(String name) {
      for (int i = 0; i < name.length(); i++) {
         char ch = name.charAt(i);
         if (!(ch >= 'a' && ch <= 'z')) {
            return false;
         }
      }
      return true;
   }
   public CustomCheckedException(String name, int age){
      if(!containsAlphabet(name)&&name!=null) {
         String msg = "Improper name (Should contain only characters between a to z (all small))";
         NotProperNameException exName = new NotProperNameException(msg);
         throw exName;
      }
      this.name = name;
      this.age = age;
   }
   public void display(){
      System.out.println("Name of the Student: "+this.name );
      System.out.println("Age of the Student: "+this.age );
   }
   public static void main(String args[]) {
      Scanner sc= new Scanner(System.in);
      System.out.println("Enter the name of the person: ");
      String name = sc.next();
      System.out.println("Enter the age of the person: ");
      int age = sc.nextInt();
      CustomCheckedException obj = new CustomCheckedException(name, age);
      obj.display();
   }
}