Java Exceptions  «Prev  Next»

Lesson 5 Catching Java Exceptions
ObjectiveCreating and Writing Catch Exceptions in Java

Creating and Writing Catch Exceptions in Java

To handle an exce ption, you must set up a special block of code. The way you set up a special block of code is by using the keywords try and catch. The idea is that you try to execute a block of code that might throw an exception. You then indicate you will catch certain (or all) exceptions which might be thrown as a result of trying to execute that block.

Diagram #4.29
Diagram #4.29
This is the basic code structure:
try{ 
/* execute code here that might cause an exception to be thrown */
}
catch(Exception e) { 
/*  handle any exceptions here that occurred in the try block */
}

Catching Exceptions

Catching exceptions is a bit like baseball .
As you can see in the code snippet above, the catch keyword is followed by a parameter definition, just as if this were defining a method parameter.
In the above example, this parameter definition is:

(Exception e)

  1. Exceptions are represented by objects.
  2. All Java exceptions are instances of subclasses of class Exception .

We will get to all the different types of Java exceptions by the end of this section.
For now, just keep in mind that the particular exception instance which gets created and thrown indicates the type of error that occurred.
The parameter following the catch keyword indicates the particular exception your code will handle in that catch block. By indicating instances of class Exception in the above example (rather than indicating an instance of a subclass of class Exception ), that catch block will handle all exceptions (that is, instances of class Exception or any of its subclasses).
You can, and you almost always should , indicate you would like to catch only a particular type of exception. For example, to catch only exceptions relating to number-formatting problems, you could write:

try{
// execute code here
}
catch(NumberFormatException e) {
// handle number format exceptions here
}

The above code indicates if any other exceptions are thrown (that is, anything other than an instance of NumberFormatException ), the exception will not be caught and handled here.
That means Java will continue to look for error-handling code by looking through the call stack, or if it does not find one, Java will handle the exception itself (and you know that means the game will end).
By handling only those exceptions you specifically anticipate, you will be certain not to hide other occurring errors that you are not aware of.