Exception Class Hierarchy
Source: exceptions1.jpg
- All Exceptions and Errors are subclasses of the Throwable superclass, which gives programs the ability to “throw” errors/exceptions.
- All checked exceptions are subclasses of the Exception class.
- All unchecked exceptions are subclasses of the RuntimeException class.
- 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");
This means that you can make a constructor in your own Exception subclasses to allow for error messages, as the following code demonstrates.
public class MyException extand Exception { public MyException() {} public MyException(Strong message) { super(message); } }
Copyright © 2021 Code 4 Tomorrow. All rights reserved.
The code in this course is licensed under the MIT License.
If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.