1 Chapter 11 Topics Exceptions Handling Exceptions

1 Chapter 11 Topics Exceptions Handling Exceptions

Date Chapter 11/6/2006 Chapter 10, start Chapter 11 11/13/2006 Chapter 11, start Chapter 12 Topics 11/20/2006 Chapter 12 11/27/2006 Chapter 13 • Exception Handling 12/4/2006 Final Exam 12/11/2006 Project Due – Using try and catch Blocks – Catching Multiple Exceptions Chapter 11 – User-Defined Exceptions • The java.io Package Exceptions • Reading from the Java Console and • Reading and Writing Text Files Input/Output Operations • Reading Structured Text Files Using StringTokenizer • Reading and Writing Objects to a File Exceptions Handling Exceptions • Java is robust language and does not allow Illegal • In a program without a Graphical User Interface, operations at run time to occur, they generate exceptions cause the program to terminate. exceptions, for example: • With this code: 12 String s = JOptionPane.showInputDialog( null, – ArrayIndexOutOfBoundsException 13 "Enter an integer" ); – ArithmeticException … – NullPointerException 17 int n = Integer.parseInt( s ); – InputMismatchException • If the user enters "a", we get this exception: – NumberFormatException • See Example 11.1 DialogBoxInput.java 1 Handling Exceptions Minimum try/catch Syntax • We don't want invalid user input to terminate the try program! { // code that might generate an exception • It is better to detect the problem and reprompt the } user for the input. catch( ExceptionClass exceptionObjRef ) • We can intercept and handle some of these { // code to recover from the exception exceptions using try and catch blocks. } – Inside the try block, we put the code that might generate an exception. • If an exception occurs in the try block, the try – Inside catch blocks, we put the code to handle any block terminates and control jumps immediately to exceptions that could be generated. the catch block. • Java provides exception classes and try, catch, and finally • If no exceptions are generated in the try block, the blocks to support exceptions catch block is not executed. Checked and Unchecked Exceptions • Java distinguishes between two types of exceptions: • Unchecked exceptions are those that are subclasses of Error or 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 try block. Otherwise, the compiler will generate an error. – IOException 2 Exception Class Exception Class Methods • Inside the catch block, you can call any of these • Is the super class of all exception classes, it methods of the Exception class: contains many predefined exceptions such as: Return value Method name and argument list – Integer divide by zero String getMessage( ) – Out-of-bound array index returns a message indicating the cause of the – Illegal number format exception String toString( ) – File does not exist returns a String containing the exception – Etc. class name and a message indicating the cause of the exception void printStackTrace( ) prints the line number of the code that caused the exception along with the sequence of method calls leading up to the exception Initializing Variables for try/catch Catching a NumberFormatException Blocks int n = 0; // declare and initialize variable • Notice that we declare and initialize the input String s = JOptionPane.showInputDialog( null, variable before we enter the try block. If we do not "Enter an integer" ); try initialize the variable and then try to access it after { the try/catch blocks, we will receive the following n = Integer.parseInt( s ); compiler error: System.out.println( "You entered " + n ); variable n might not have been initialized } catch ( NumberFormatException nfe ) The error indicates that the only place where n is { assigned a value is in the try block. If an exception System.out.println( "Incompatible data." ); occurs, the try block will be interrupted and we might } not ever assign n a value. • See Example 10.2 DialogBoxInput.java • Initializing the value before entering the try block solves this problem. public static int parseInt (String str) throws NumberFormatExeption 3 Recovering From an Exception int n = 0; • The previous code just printed a message when the boolean goodInput = false; // flag variable exception occurred. String s = JOptionPane.showInputDialog( null, • To continue processing and reprompt the user for "Enter an integer" ); do { good input, we can put the try and catch blocks try { inside a do/while loop. n = Integer.parseInt( s ); goodInput = true; //executed if no exception } • See Example 11.3 DialogBoxInput.java (next catch ( NumberFormatException nfe ) { s = JOptionPane.showInputDialog( null, Slide) s + " is not an integer. " + "Enter an integer" ); } } while ( ! goodInput ); Software Engineering Tip Catching Multiple Exceptions • If the code in the try block might generate Write code to catch and handle exceptions multiple, different exceptions, we can provide generated by invalid user input. multiple catch blocks, one for each possible exception. Although the methods of the Exception class are good debugging tools, they are not necessarily • When an exception is generated, the JVM searches appropriate to use in the final version of a the catch blocks in order. The first catch block program. with a parameter that matches the exception thrown will execute; any remaining catch blocks will be skipped. Always try to write code that is user-friendly. 4 catch Block Order The finally Block • An exception will match any catch block with a • Optionally, you can follow the catch blocks with a parameter that names any of its superclasses. finally block. – For example, a NumberFormatException will match a • The finally block will be executed whether or not catch block with a RuntimeException parameter. an exception occurs. Thus: – All exceptions will match a catch block with an – if an exception occurs, the finally block will be Exception parameter. executed when the appropriate catch block finishes executing • Thus, when coding several catch blocks, arrange – if no exception occurs, the finally block will be the catch blocks with the specialized exceptions executed when the try block finishes first, followed by more general exceptions. • For example, a finally block might be used to close an open file. We demonstrate this later. Full try/catch/finally Syntax try Catching Multiple Exceptions { // code that might generate an exception • We can write a program that catches several } catch ( Exception1Class e1 ) exceptions. { • For example, we can prompt the user for a divisor. // code to handle an Exception1Class exception } – If the input is not an integer, we catch the … NumberFormatException and reprompt the user with an catch ( ExceptionNClass eN ) appropriate message. { – If the input is 0, we catch an ArithmeticException when // code to handle an ExceptionNClass exception we attempt to divide by 0, and reprompt the user with } an appropriate message. finally { // code to execute in any case • See Example 11.4 Divider.java } 5 User-Defined Exceptions User-Defined Exception • We can design our own exception class. • Java has an IllegalArgumentException class, so • Suppose we want to design a class encapsulating our IllegalEmailException class can be a subclass email addresses ( EmailAddress class ). of the IllegalArgumentException class. – For simplicity, we say that a legal email address is a String containing the @ character. • By extending the IllegalArgumentException class: – we inherit the functionality of an exception class, which • Our EmailAddress constructor will throw an simplifies our coding of the exception exception if its email address argument is illegal. – we can associate a specific error message with the exception • To do this, we design an exception class named IllegalEmailException . Extending an Existing Exception Throwing an Exception • The pattern for a method that throws a user-defined • We need to code only the constructor, which exception is: accepts the error message as a String. accessModifier returnType methodName( parameters ) • General pattern: throws ExceptionName public class ExceptionName { extends ExistingExceptionClassName if( parameter list is legal ) { process the parameter list public ExceptionName( String message ) else { throw new ExceptionName( "Message here" ); super( message ); } } • The message passed to the constructor identifies the } error we detected. In a client's catch block, the getMessage method will retrieve that message. • See Example 11.5 IllegalEmailException.java • See Examples 11.6 & 11.7 6 System.in Object Class BufferReader (returns String) Class InputStreamReader (returns unicode characters) java.io Package Object InputStream System.in Returns bytes A set of classes used for: reading and writing from files reading from console BufferedReader inStream = new BufferedReader(new InputStreamReader(System.in)); Selected Input Classes in Hierarchy for Input Classes the java.io Package Class Description Reader Abstract superclass for input classes InputStream Abstract superclass representing a stream of raw bytes InputStreamReader Class to read input data streams FileReader Class to read character files Class to read input data streams BufferedReader Class providing more efficient reading of character files FileInputStream Input stream to read raw bytes of data

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    18 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us