* Custom exceptions are user created exceptions.
* Custom exceptions are used to set the own message to the exception. So the developer easily understands the exception.
We can create our own exception by extends the Exception class.
class InvalidNumberException extends Exception{
public InvalidNumberException(String message) {
// TODO Auto-generated constructor stub
super(message);
}
}
* When throw the exception you should throws the exception or catch the exception.
public static void main(String[] args) throws InvalidNumberException {
System.out.println("Enter number 1 - 9");
Scanner in = new Scanner(System.in);
int a = in.nextInt();
if(a < 1 || a > 10){
throw new InvalidNumberException("Invalid number");
} else {
System.out.println("Valid number "+a);
}
}
Download Custom Exception source code
* Custom exceptions are used to set the own message to the exception. So the developer easily understands the exception.
We can create our own exception by extends the Exception class.
class InvalidNumberException extends Exception{
public InvalidNumberException(String message) {
// TODO Auto-generated constructor stub
super(message);
}
}
* When throw the exception you should throws the exception or catch the exception.
public static void main(String[] args) throws InvalidNumberException {
System.out.println("Enter number 1 - 9");
Scanner in = new Scanner(System.in);
int a = in.nextInt();
if(a < 1 || a > 10){
throw new InvalidNumberException("Invalid number");
} else {
System.out.println("Valid number "+a);
}
}
Download Custom Exception source code
No comments:
Post a Comment