Source: exceptions1.jpg
You can create your own classes in Java for exceptions that are specific to your program. Extend the Exception class or the RuntimeException class, depending on whether you want your exception to be checked or unchecked.
public class MyException extends Exception {
}
If the above code is in a separate file (MyException.java), this is enough to be able to throw a new exception:
public static void main(String[] args) {
try {
call(null);
} catch(MyException e) {
System.out.println("Caught MyException");
}
}
public static void call(String s) throws MyException {
if (s == null)
throw new MyException();
}
You can add constructors or other methods to your Exception subclass if you want. The pre-made Java Exception subclasses (like ArithmeticException and IOException) allow you to pass an error message as a parameter when you throw them:
throw new ArithmeticException("divide by zero error");