What are exceptions?-----------------------------------------------------
An exception is Java's method of handling errors that occur while running the program.
This relatively simple chunk of code looks for a file named
readme.txt, and opens it without reading it or doing anything once it is opened. The important thing is that if
readme.txt doesn't exist, calling the constructor method
FileInputStream() will send an exception named
FileNotFoundException, strangely enough.
So how do we deal with pesky exceptions? One way to prevent exceptions from prematurely ending a program is to put them in a
try..catch block:
java code
try {
FileInputStream fileopener = new FileInputStream("readme.txt");
}
catch(FileNotFoundException ex) {
System.out.println("An exception has occured:\n" + ex.getMessage());
}
What the try..catch block does is attempt to do whatever is in the try block--in this case, opening a file. If the file doesn't exist, it will throw the
FileNotFoundException. This time, control will move to the catch block, where the exception has been "caught," and Java will do whatever in the
block--in this case, print the words "An exception has occurred:", followed by the message embedded in the exception. (As you might have noticed, exceptions, like many things in Java, are objects, and as such have their own methods.)
Analyzing exceptions:
There are two ways to deal with exceptions: - Handle the exception right where it occurs
- Throw the exception on to the next method
We have already looked at handling the exception immediately by using try..catch statements. You can use catch to clean up unfinished business, explain what kind of error occurred--whatever you'd like, as long as it doesn't depend on anything succeeding in the try block. If you choose to throw the exception, you simply pass it on. Exceptions start in the method where they originated and "bubble up." For example:
java code
public static void parent() {
child();
}
public static void child throws FileNotFoundException() {
grandchild();
}
public static void grandchild throws FileNotFoundException() {
FileInputStream fileopener = new FileInputStream("readme.txt");
}
If it turns out the file
readme.txt doesn't exist,
FileInputStream() will send an exception to
grandchild(), who will send it to child(), who will send it to parent(). At some point, of course, the exception has to be caught; where this is is up to you. To have methods throw exceptions, add the words throws (name of exception) at the end of the line declaring the method. Any exception that isn't in a try..catch block will be bubbled up.