Page 605 - Introduction to Programming with Java: A Problem Solving Approach
P. 605
specifically, the program calls a File constructor, it calls File’s exists method, and it calls File’s createFile method. As with many file-related API calls, those calls all have the potential of throwing an exception. So how should you deal with that? Read on. . . .
Using API Documentation When Writing Exception Handling Code
Whenever you want to use a method or constructor from one of the API classes and you’re not sure about it, you should look it up in the API documentation so you know whether to add exception handling code. On the API documentation page for the method or constructor of interest, look for a “throws” section, which identifies specific types of exceptions that might be thrown. To handle the exceptions, you need to under- stand them. To understand a particular exception, click on its link in the throws section. That should take you to the API documentation for the exception’s class.
On the exception class’s API page, scroll down a bit and read the exception class’s description. Then scroll back up and look at the class’s class hierarchy. As mentioned previously, if RuntimeException is an ancestor, the exception is an unchecked exception. Otherwise, it’s a checked exception.
Back to the CreateNewFile Program
If you apply the above API-lookup strategy to the CreateNewFile program, you’ll find that:
• The File constructor call throws a NullPointerException if its argument is null. The NullPointerException class is derived from the RuntimeException class, so it’s an un- checked exception. The code is written so that there’s no danger of the File constructor’s argument being null, so there’s no need to add any code for the File constructor call.
• ThecreateNewFilemethodcallthrowsanIOExceptionifthere’sanI/Oproblemlikeacorrupt hard disk or an invalid directory name. The IOException class is derived from the Exception class but not from the RuntimeException class, so it is a checked exception. Thus, we’re required to add try-catch code to handle this exception.
Because of the createNewFile method call, Figure 14.11’s CreateNewFile program doesn’t compile suc- cessfully. What’s the solution? Suppose you simply surround the createNewFile method call with a try block like this:
else
}
}
{
}
System.out.println("File I/O error");
file.createNewFile();
catch (IOException ioe)
Apago PDF Enhancer
• The exists method call throws a SecurityException if a security manager exists. The SecurityException class is derived from the RuntimeException class, so it’s an unchecked exception. If you don’t have a security manager, there’s no need to add any code for the exists method call.
{
try
{
System.out.println(fileName + " created.");
14.8 CheckedExceptions 571