Exception Class Hierarchy

https://s3.amazonaws.com/thinkific/file_uploads/288722/images/366/4d7/32b/1600549104979.jpg

Source: exceptions1.jpg

  1. All Exceptions and Errors are subclasses of the Throwable superclass, which gives programs the ability to “throw” errors/exceptions.
  2. All checked exceptions are subclasses of the Exception class.
  3. All unchecked exceptions are subclasses of the RuntimeException class.
  4. Errors will not be discussed in detail, but these signify serious and/or abnormal problems that you should not try to catch because it could potentially be dangerous. The purpose of this class is mainly to provide information about the error.

User-Defined Exceptions

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");