Unformatted text preview:

1Chapter 11Exceptions and Input/Output OperationsDate Chapter11/6/2006 Chapter 10, start Chapter 1111/13/2006 Chapter 11, start Chapter 1211/20/2006 Chapter 1211/27/2006 Chapter 1312/4/2006 Final Exam12/11/2006 Project DueTopics• Exception Handling– Using try and catch Blocks– Catching Multiple Exceptions– User-Defined Exceptions• The java.io Package• Reading from the Java Console• Reading and Writing Text Files• Reading Structured Text Files Using StringTokenizer• Reading and Writing Objects to a FileExceptions• Java is robust language and does not allow Illegal operations at run time to occur, they generate exceptions, for example:– ArrayIndexOutOfBoundsException– ArithmeticException– NullPointerException– InputMismatchException– NumberFormatExceptionHandling Exceptions• In a program without a Graphical User Interface, exceptions cause the program to terminate.• With this code:12 String s = JOptionPane.showInputDialog( null, 13 "Enter an integer" );…17 int n = Integer.parseInt( s );• If the user enters "a", we get this exception:• See Example 11.1 DialogBoxInput.java2Handling Exceptions• We don't want invalid user input to terminate the program! • It is better to detect the problem and reprompt the user for the input.• We can intercept and handle some of these exceptions using try and catch blocks.– Inside the try block, we put the code that might generate an exception.– Inside catch blocks, we put the code to handle any exceptions that could be generated.• Java provides exception classes and try, catch, and finally blocks to support exceptionsMinimum try/catch Syntaxtry{// code that might generate an exception}catch( ExceptionClass exceptionObjRef ){// code to recover from the exception}• If an exception occurs in the try block, the tryblock terminates and control jumps immediately to the catch block.• If no exceptions are generated in the try block, the catch block is not executed.Checked and Unchecked Exceptions• Java distinguishes between two types of exceptions:• Unchecked exceptions are those that are subclasses of Erroror RuntimeException– It is not mandatory to use try and catch blocks to handle these exceptions.– If you omit try and catch blocks your code will compile.– If they occur the JVM will catch and display the error message.– ArithmeticException (caused by divide by zero), NumberFormatException, NullPointerException• Checked exceptions are any other exceptions.– Code that might generate a checked exception must be put inside a tryblock. Otherwise, the compiler will generate an error.– IOException3Exception Class• Is the super class of all exception classes, it contains many predefined exceptions such as:– Integer divide by zero– Out-of-bound array index– Illegal number format– File does not exist– Etc.Exception Class Methods• Inside the catch block, you can call any of these methods of the Exception class:printStackTrace( )prints the line number of the code that caused the exception along with the sequence of method calls leading up to the exceptionvoidtoString( )returns a String containing the exception class name and a message indicating the cause of the exceptionString getMessage( )returns a message indicating the cause of the exceptionStringMethod name and argument listReturn valueCatching a NumberFormatExceptionint n = 0; // declare and initialize variableString s = JOptionPane.showInputDialog( null,"Enter an integer" ); try{n = Integer.parseInt( s );System.out.println( "You entered " + n );}catch ( NumberFormatException nfe ){System.out.println( "Incompatible data." );}• See Example 10.2 DialogBoxInput.javapublic static int parseInt (String str) throws NumberFormatExeptionInitializing Variables for try/catchBlocks• Notice that we declare and initialize the input variable before we enter the try block. If we do not initialize the variable and then try to access it after the try/catch blocks, we will receive the following compiler error: variable n might not have been initializedThe error indicates that the only place where n is assigned a value is in the try block. If an exception occurs, the try block will be interrupted and we might not ever assign n a value.• Initializing the value before entering the try block solves this problem.4Recovering From an Exception• The previous code just printed a message when the exception occurred. • To continue processing and reprompt the user for good input, we can put the try and catch blocks inside a do/while loop.• See Example 11.3 DialogBoxInput.java (next Slide)int n = 0;boolean goodInput = false; // flag variableString s = JOptionPane.showInputDialog( null,"Enter an integer" );do {try {n = Integer.parseInt( s );goodInput = true; //executed if no exception }catch ( NumberFormatException nfe ) {s = JOptionPane.showInputDialog( null,s + " is not an integer. "+ "Enter an integer" );}} while ( ! goodInput );Software Engineering Tip Write code to catch and handle exceptions generated by invalid user input. Although the methods of the Exception class are good debugging tools, they are not necessarily appropriate to use in the final version of a program. Always try to write code that is user-friendly.Catching Multiple Exceptions• If the code in the try block might generate multiple, different exceptions, we can provide multiple catch blocks, one for each possible exception. • When an exception is generated, the JVM searches the catch blocks in order. The first catch block with a parameter that matches the exception thrown will execute; any remaining catch blocks will be skipped.5catch Block Order• An exception will match any catch block with a parameter that names any of its superclasses. – For example, a NumberFormatException will match a catch block with a RuntimeException parameter.– All exceptions will match a catch block with an Exception parameter. • Thus, when coding several catch blocks, arrange the catch blocks with the specialized exceptions first, followed by more general exceptions. The finally Block• Optionally, you can follow the catch blocks with a finally block.• The finally block will be executed whether or not an exception occurs. Thus:– if an exception occurs, the finally block will be executed when the appropriate catch block finishes executing– if no exception occurs, the finally block will be executed when the try block finishes• For example, a finally block


View Full Document

IIT CS 201 - Chapter 11 Eceptions

Download Chapter 11 Eceptions
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Chapter 11 Eceptions and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Chapter 11 Eceptions 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?