J2EEOnline
GofPatterns OOPortal
prev next prev next
  Course navigation
 
Lesson 9
Objective
Defining your own exceptions
Create your own exception subclass.
   
There is no reason you must restrict yourself to the Exception subclasses defined in Java's libraries. You can create your own!
The easiest way to define your own exception is to simply subclass Exception, even to the point of not defining any extensions to the Exception class, like this:
class MyException 
extends Exception { 
} 
In this case, you are letting the name of the class provide all the new information you need (that is, you don't want the new exception to behave any differently than the default; you just want to be able to identify this exception in a catch block).
You can also provide a String that describes something more about this exception when you create it. To do so, you can provide a class definition and constructor that looks something like this:
class MyException extends Exception {
   MyException (String s) { 
      super(s); 
   } 
} 
The Exception class extends a class called Throwable. This class defines a few methods you can use to extract more information from this exception. For example, getMessage() retrieves the string describing the exception, and printStackTrace() prints the call stack up to the exception. Java's documentation for Throwable contains additional, in-depth information.
Exercise: Throw an exception
This exercise gives you a chance to create your own exception and use it in a program.
Java Throwing Exceptions Exercise
User Defined Exceptions Quiz
Click on the quiz link below to review exceptions.
User Defined Exceptions Quiz
  Course navigation