How can I write custom Exceptions?
JavaExceptionJava Problem Overview
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.
Java Solutions
Solution 1 - Java
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 - Java
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 - Java
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.)
Solution 4 - Java
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.
Solution 5 - Java
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();
}
}