To create your own throwable exception, you should extend your exceptions from the exception class.

Before you can catch an exception, some code somewhere must throw one. Any code can throw an exception: your code, code from a package written by someone else such as the packages that come with the Java platform, or the Java runtime environment. Regardless of what throws the exception, it's always thrown with the throw statement.

As you have probably noticed, the Java platform provides numerous exception classes. All the classes are descendants of the Throwable class, and all allow programs to differentiate among the various types of exceptions that can occur during the execution of a program.

You can also create your own exception classes to represent problems that can occur within the classes you write. In fact, if you are a package developer, you might have to create your own set of exception classes to allow users to differentiate an error that can occur in your package from errors that occur in the Java platform or other packages.

You can also create chained exceptions. For more information, see the Chained Exceptions section.

The throw Statement

All methods use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object. Throwable objects are instances of any subclass of the Throwable class. Here's an example of a throw statement.

throw someThrowableObject;

Let's look at the throw statement in context. The following pop method is taken from a class that implements a common stack object. The method removes the top element from the stack and returns the object.

public Object pop() { Object obj; if (size == 0) { throw new EmptyStackException(); } obj = objectAt(size - 1); setObjectAt(size - 1, null); size--; return obj; }

The pop method checks to see whether any elements are on the stack. If the stack is empty (its size is equal to 0), pop instantiates a new EmptyStackException object (a member of java.util) and throws it. The Creating Exception Classes section in this chapter explains how to create your own exception classes. For now, all you need to remember is that you can throw only objects that inherit from the java.lang.Throwable class.

Note that the declaration of the pop method does not contain a throws clause. EmptyStackException is not a checked exception, so pop is not required to state that it might occur.

Throwable Class and Its Subclasses

The objects that inherit from the Throwable class include direct descendants (objects that inherit directly from the Throwable class) and indirect descendants (objects that inherit from children or grandchildren of the Throwable class). The figure below illustrates the class hierarchy of the Throwable class and its most significant subclasses. As you can see, Throwable has two direct descendants: Error and Exception.

To create your own throwable exception, you should extend your exceptions from the exception class.

The Throwable class.

Error Class

When a dynamic linking failure or other hard failure in the Java virtual machine occurs, the virtual machine throws an Error. Simple programs typically do not catch or throw Errors.

Exception Class

Most programs throw and catch objects that derive from the Exception class. An Exception indicates that a problem occurred, but it is not a serious system problem. Most programs you write will throw and catch Exceptions as opposed to Errors.

The Java platform defines the many descendants of the Exception class. These descendants indicate various types of exceptions that can occur. For example, IllegalAccessException signals that a particular method could not be found, and NegativeArraySizeException indicates that a program attempted to create an array with a negative size.

One Exception subclass, RuntimeException, is reserved for exceptions that indicate incorrect use of an API. An example of a runtime exception is NullPointerException, which occurs when a method tries to access a member of an object through a null reference. The section Unchecked Exceptions — The Controversy discusses why most applications shouldn't throw runtime exceptions or subclass RuntimeException.

This Java tutorial guides you on how to create your own exceptions in Java.In the article Getting Started with Exception Handling in Java, you know how to catch throw and catch exceptions which are defined by JDK such as IllegalArgumentException, IOException, NumberFormatException, etc.What if you want to throw your own exceptions? Imagine you’re writing a student management program and you want to throw StudentException, StudentNotFoundException, StudentStoreException and the like?So it’s time to create new exceptions of your own.We will call JDK’s exceptions built-in exceptions and call our own exceptions custom exceptions.Let me tell you this: Writing custom exceptions in Java is very easy, but the important thing is, you should ask yourself this question: 

1. Why do I need custom exceptions?

Why do we need to create a new exception, instead of using the ones defined by JDK?The answer could be very simple: When you couldn’t find any relevant exceptions in the JDK, it’s time to create new ones of your own.But, how do we know which exception is relevant, which is not?By looking at the names of the exceptions to see if its meaning is appropriate or not. For example, the IllegalArgumentException is appropriate to throw when checking parameters of a method; the IOException is appropriate to throw when reading/writing files.From my experience, most of the cases we need custom exceptions for representing business exceptions which are, at a level higher than technical exceptions defined by JDK. For example: InvalidAgeException, LowScoreException, TooManyStudentsException, etc. 

2. Writing your own exception class

Now, let’s see how to create a custom exception in action. Here are the steps:
  • Create a new class whose name should end with Exception like ClassNameException. This is a convention to differentiate an exception class from regular ones.
  • Make the class extends one of the exceptions which are subtypes of the java.lang.Exception class. Generally, a custom exception class always extends directly from the Exception class.
  • Create a constructor with a String parameter which is the detail message of the exception. In this constructor, simply call the super constructor and pass the message.
That’s it. The following is a custom exception class which is created by following the above steps:public class StudentNotFoundException extends Exception { public StudentNotFoundException(String message) { super(message); } }And the following example shows the way a custom exception is used is nothing different than built-in exception:public class StudentManager { public Student find(String studentID) throws StudentNotFoundException { if (studentID.equals("123456")) { return new Student(); } else { throw new StudentNotFoundException( "Could not find student with ID " + studentID); } } }And the following test program handles that exception:public class StudentTest { public static void main(String[] args) { StudentManager manager = new StudentManager(); try { Student student = manager.find("0000001"); } catch (StudentNotFoundException ex) { System.err.print(ex); } } }Run this program and you will see this output:StudentNotFoundException: Could not find student with ID 0000001 

3. Re-throwing an exception which is wrapped in a custom exception

It’s a common practice for catching a built-in exception and re-throwing it via a custom exception. To do so, let add a new constructor to our custom exception class. This constructor takes two parameters: the detail message and the cause of the exception. This constructor is implemented in the Exception class as following:      public Exception(String message, Throwable cause)Besides the detail message, this constructor takes a Throwable’s subclass which is the origin (cause) of the current exception. For example, create the StudentStoreException class as following:public class StudentStoreException extends Exception { public StudentStoreException(String message, Throwable cause) { super(message, cause); } }And the following example shows where the StudentStoreException gets thrown:public void save(Student student) throws StudentStoreException { try { // execute SQL statements.. } catch (SQLException ex) { throw new StudentStoreException("Failed to save student", ex); } }Here, suppose that the save() method stores the specified student information into a database using JDBC. The code can throw SQLException. We catch this exception and throw a new StudentStoreException which wraps the SQLException as its cause. And it’s obvious that the save() method declares to throw StudentStoreException instead of SQLException.So what is the benefit of re-throwing exception like this?Why not leave the original exception to be thrown?Well, the main benefit of re-throwing exception by this manner is adding a higher abstraction layer for the exception handling, which results in more meaningful and readable API. Do you see StudentStoreException is more meaningful than SQLException, don’t you?However, remember to include the original exception in order to preserve the cause so we won’t lose the trace when debugging the program when the exception occurred.And the following code demonstrates handling the StudentStoreException above:StudentManager manager = new StudentManager(); try { manager.save(new Student()); } catch (StudentStoreException ex) { System.err.print(ex); }That’s about the lesson of writing custom exceptions in Java. 

References:

  • Lesson: Exceptions in the Java Tutorials
 

Other Java Exception Handling Tutorials:

 


To create your own throwable exception, you should extend your exceptions from the exception class.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.