Home » Java Basics » 05 - Files, Collections, and Exceptions
5

Exceptions

Information about the type of error and the statement that caused the error

Errors during runtime cause the creation of a special Exception Object in the method where the error occurred. The generation of an Exception Object upon error is called throwing an exception. The Exception object contains details about the type of error and the statement that caused the error. The runtime environment tries to find a way to handle the error by checking to see if Exception Handlers - code that specifies the actions to take if an errors occur - exist in all the methods (starting from a main method) that were invoked to get to the method that caused the error. For example, if Class A calls Method B and Method B invokes Method C. Suppose an error of type X occurs in method C. A, B, and C are searched for Exception Handlers that catch exceptions of type X. If such a handler exists, the error is dealt with in a graceful way. Otherwise, the runtime environment exits with an error status.

Java Exceptions are classified into checked exceptions, Errors, and Runtime Exceptions. Handling the first type of exception in code is compulsory. Checked exceptions may be easily anticipated and well written programs will be able to handle them automatically. For example, a popular checked exception 'java.io.FileNotFoundException' is thrown when a directory or file is not found in a specified path. A programmer should include an exception handler for this exception whenever code that will try to open a file is put in..

The Java platform provides several exception classes that are all subclasses of the Throwable class. These classes may be used to easily determine the nature and cause of the exception.

Exceptions of type error have nothing to do with the application; errors occur when the OS malfunctions or when some device is not available for communication, and so on. The most ubiquitous Java Runtime Exception is 'NullPointerException'. Runtime exceptions are usually a result of sloppy code that does not handle all the possibilities. Errors and Runtime Exceptions are called Unchecked Exceptions. Handling such exceptions is not compulsory but useful as they can reveal important information about bug-prone sections or system malfunctions. Exceptions may be handled by a try-catch loop. Also, entire methods or classes may throw exceptions. The following code illustrates catching an exception within a method C:

public int C (String S) {
try {
// Some code that causes 'ExceptionX' or 'ExceptionY'
// (these represent subclasses of Throwable)
 
} catch (exceptionX e) {
System.err.println("I just handled this error: "
+ e.getMessage());
 
} catch (exceptionY e) {
System.err.println("I just handled another error: "
+ e.getMessage());
}
finally {
//Code to shut application; proceed in another way etc.
}
}

Normally, the first 'try' section(s) catch specific errors and the last 'try' section catches general errors (perhaps just 'Exception' - the most general class that would catch any exception at all.) The 'finally' section contains actions to take before exiting the application or stopping the process that caused the exceptions. Sometimes, developers may decide to incorporate the try-catch loop higher up in the stack. That is, if the code in method C may cause Exception X and Exception Y, and was called by method B, they may simply declare that method C 'throws' the exceptions instead of putting a try catch loop within method C:

  public int C (String S) throws ExceptionX, ExceptionY   {
 
// Some code that causes 'ExceptionX' or 'ExceptionY'
// (these represent subclasses of Throwable)
 
}

Thus, the throw statement becomes part of the method signature. Now, method B, the method that calls method C, should contain the try catch loops that catch the errors thrown by method C.

public void B ()    {
 
try {
 
int i = C("hello"); // Method C is called.
// Exceptions thrown by C are
// handled.
 
} catch (exceptionX e) {
System.err.println("I just handled this error: "
+ e.getMessage());
 
} catch (exceptionY e) {
System.err.println("I just handled another error: "
+ e.getMessage());
}
finally {
//Code to shut application; proceed in another way etc.
}
 
}

Also, the 'throw' keyword may be used to throw an exception within a method. Any method that contains a 'throw' statement has to include the 'throws' clause in its signature for the corresponding Exception.

           throw new ExceptionX();

The following is the source file for the exception InputFileFormatException thrown in the createFruits application if the input file is of the wrong format. This is a custom Exception class created for the Fruits Application; the constructor simply sets the message that will be displayed when an error occurs.

/**
* @author Java Student
*/
public class InputFileFormatException extends java.lang.Exception {
/**
* Constructs an instance of InputFileFormatException
* with the specified detail message.
* @param msg the detail message
*/
public InputFileFormatException(String msg) {
super(msg);
}
}

Each line in the input file should contain the four properties of a fruit separated by semicolons. The split method with a semicolon (;) as its delimeter is invoked for each retrieved line. If the resulting array does not contain four elements, the input file becomes invalid and the InputFileFormatException is thrown.

fruitProperties = lineFromFile.split(";");
if (fruitProperties.length != 4){
throw new InputFileFormatException("Error in Parameter File Format!");
}

As InputFileFormatException is thrown within the main method, the main method's signature contains a 'throws' clause.

public static void main(String[] args) throws InputFileFormatException {

The main method of createFruits.java also contains a try-catch section to handle exceptions that occur when the java.io.BufferedReader and java.io.FileReader classes try to access a file that does not exist or when there is a problem with reading the data. Basically, these errors occur if the input file is not found in the specified path (specified as an argument to the 'java' command while running the application) or if there is a problem reading from the file (the file may already be open or the user does not have a write permission).

try {
imageInput =  new BufferedReader(new FileReader(new File(path))) ;
imagePath = imageInput.readLine();
.
.
..java Code..
.
.
}
catch (java.io.FileNotFoundException fnf) {
System.out.println("Input File not Found: " + fnf.getMessage());
}
catch (java.io.IOException ioe) {
System.out.println("Problems Reading File: " + ioe.getMessage());
}