Java User Defined Exception Example
Chapter:
Exception Handling
Last Updated:
05-09-2016 17:02:06 UTC
Program:
/* ............... START ............... */
class WrongInputException extends Exception {
WrongInputException(String s) {
super(s);
}
}
class Input {
void method() throws WrongInputException {
throw new WrongInputException("Wrong input");
}
}
public class JavaUserDefinedException {
public static void main(String[] args) {
try {
new Input().method();
} catch (WrongInputException wie) {
System.out.println(wie.getMessage());
}
}
}
/* ............... END ............... */
Output
Notes:
-
User defined exceptions in java are also known as Custom exceptions.
- User defined exception needs to inherit (extends) Exception class in order to act as an exception.
- throw keyword is used to throw such exceptions.
Tags
User Defined Exception, Exception, Java