CS 209 Programming in Java #10 Exception Handling Textbook Chapter 15 Spring, 2006 Instructor: J.G. Neal 1 Topics What is an Exception? Exception Handling Fundamentals Errors and Exceptions The try-catch-finally Structure The try, catch, and finally Blocks Selected Methods in Class Throwable Example Program Throwing an Exception Another Example Program 2
Types of Errors There are three types of errors: Syntax error: A violation of the grammar rules that define legal code. These rules define the legal use of the programming language with respect to the identifiers, keywords, symbols, literals, and expressions used and their arrangement. Can you give examples? Detected when? Detected by what? Runtime error: An error situation that arises during program execution; an illegal operation is performed Can you give examples? Detected when? Detected by what? Logical error: The program produces incorrect output results Can you give examples? Detected when? Detected by what? 3 What is an exception? Why is exception handling important? An exception is: An indication that a problem occurred during program execution (runtime) An unexpected condition or error condition Exception handling is important Purpose: To support robust, fault-tolerant programs Objective: Separation of error handling code from the program code that implements the required objects and functionality 4
When can exceptions occur? Exceptions occur when a program tries to perform runtime operations such as: Divide by zero Pass invalid parameters to a method Use a null reference (pointer) to access a method in a class Convert data to an incompatible type among others... Can you list other examples? 5 Partial Java Class Hierarchy AWTError LinkageError Error ThreadDeath Object Throwable VirtualMachineError BadLocationException (java.swing.text) Exception DataFormatException (java.util.zip) IOException (java.io) SQLException (java.sql) RuntimeException 6
Error Error class: A subclass of the Throwable class Purpose: Indicate serious problems that a reasonable application should not try to catch Most such errors are abnormal conditions Example: Subclasses of LinkageError indicate that a class has some dependency on another class; however, the latter class has incompatibly changed after the compilation of the former class Note: ThreadDeath error: Though a "normal" condition, is also a subclass of Error because most applications should not try to catch it 7 Exception The Exception class and its subclasses: A type of Throwable that indicates conditions that a reasonable application might want to catch and handle Exception handling: Deal with synchronous errors that occur as the program executes certain instructions Examples: out-of-bounds array subscript, division by zero, null pointer, invalid method parameters, file not found, class cast problem, bad location in text document Not designed to deal with asynchronous events Examples: disk I/O completions, network message arrivals, user manipulation of GUI widgets Use event listeners for these 8
What can you do with exceptions? Program code can do the following: Catch and handle exceptions Throw exceptions Define new types of exceptions Define methods that throw exceptions 9 The try-catch-finally structure Purpose: to catch and handle exceptions try block: Encloses the code that may generate an exception catch block: Zero or more catch blocks immediately follow the try block Each specifies the type of exception it can catch Each contains an exception handler finally block: Optional Provides code that always executes regardless of whether or not an exception occurs If no catch blocks, then the finally block is required Commonly used to return resources to the system e.g., close any files opened in the try block 10
Syntax try { // statements; // resource-acquisition statements; } catch ( ExceptionType1 ex1 ) { // exception-handling statements; } catch ( ExceptionType2 ex2 ) { // exception-handling statements; } finally { // optional block if a catch block is present // statements; // resource-release statements; } 11 Example try { // Convert numbers from type String to type int int1 = Integer.parseInt( firstinteger ); int2 = Integer.parseInt( secondinteger ); } catch( NumberFormatException ex ) { // Display error message via JOptionPane String msg = Illegal input in text field\n + Please enter the number again ; JOptionPane.showMessageDialog( null, msg, Error Message, JOptionPane.PLAIN_MESSAGE); return; } 12
The try-catch-finally structure How it works When an exception is thrown, program control exits the try block and searches the catch blocks for an appropriate handler If the type of the thrown exception matches the parameter type in one of the catch blocks, the code for that catch block is executed If no exceptions are thrown, the catch blocks are skipped and program execution resumes after the last catch block If a finally block appears after the last catch block, it is executed regardless of whether or not an exception is thrown 13 Useful Methods in Class Throwable getmessage() object - Returns the error message string of this Throwable printstacktrace() - Prints this Throwable object and its backtrace to the standard error stream printstacktrace( PrintStream s ) - Prints this Throwable object and its backtrace to the specified print stream tostring() - Returns a short description of this Throwable object 14
Example Program Purpose: To demonstrate exceptions and The use of exception handling Program: Project: ExceptionsExs Package: exceptionexs File: NumberFormatEx.java Questions: See next slides (continued on next slide) 15 Example Program Questions: Where do you place a try-catch structure? What do you put in the try block? What do you put in the catch block? What are some action choices when catching and handling an exception? (continued on next slide) 16
Example Program Questions: Can the program get the erroneous characters entered (for display to user)? Does the program detect all error conditions and notify the user? What happens in the case of an exception that is not detected by our program? How can we change the program so that it can tell the user which text field contains the illegal input? Show the difference between using tostring() and getmessage() Demonstrate the use of multiple catch blocks Demonstrate that a finally block will always be executed 17 Example Program 18
Printing C:\Documents and Settings\jgneal\My Documents\MyDev\MyJava\Exceptions\ExceptionExs\src\exceptionexs\NumberFormatEx.java a 1 package 2 import 3 import 4 import 5 import 6 7 public class NumberFormatEx extends JFrame implements ActionListener { 8 // Instance variables 9 private // Present instructions to user 10 private // Prompts for user input 11 private // Mechanisms to get user input 12 13 private int int1, // First integer from user // Second integer from user 15 16 private int sum, // Sum of the two input integers 17 difference, // Difference of the two input integers 18 product, // Product of the two input integers 19 quotient, // Quotient of the two input integers // Remainder from the two input integers 21 22 private // Output display area 23 private int // Width of the JTextArea 24 private int // Height of the JTextArea 25 26 // The main method required for an application program 27 public static void main( String[] args ) { 28 JFrame frame = new NumberFormatEx // Construct the window 29 frame.setsize( new Dimension // Set its size 30 frame.setdefaultcloseoperation 31 frame.setvisible( true // Make the window visible 32 } 33 34 // Constructor 35 public NumberFormatEx() { 36 super 37 Container c = getcontentpane 38 c.setlayout( new BorderLayout 39 40 JPanel jpan = new JPanel(new GridLayout 42 jpan.setborder(new TitledBorder 43 44 prompt1 = new JLabel 45 jpan.add // put prompt on window 46 input1 = new JTextField 47 jpan.add // put input JTextField on window 48 Page 1
Printing C:\Documents and Settings\jgneal\My Documents\MyDev\MyJava\Exceptions\ExceptionExs\src\exceptionexs\NumberFormatEx.java a 49 prompt2 = new JLabel 50 jpan.add // put prompt on window 51 input2 = new JTextField 52 jpan.add // put input JTextField on window 53 54 c.add 55 56 // Create and display a text area for presenting results 57 TDisplay = new JTextArea( composedisplaystring(), 59 TDisplay.setLineWrap( true 60 TDisplay.setWrapStyleWord( true 61 c.add 62 63 // "this" window will respond to user input in text fields 64 input1.addactionlistener ( this 65 input2.addactionlistener ( this 66 } 67 68 // Process user's action in JTextField input 69 public void actionperformed ( ActionEvent e) { 70 // Get the string data from the JTextFields 71 String firstinteger = input1.gettext 72 String secondinteger = input2.gettext 73 74 try { // Convert numbers from type String to type int 75 int1 = Integer.parseInt 76 int2 = Integer.parseInt 77 } 78 catch( NumberFormatException ex ) { 79 // Display error message via JOptionPane 80 81 String msg = "Illegal input in text field\nplease enter the 82 JOptionPane.showMessageDialog( 83 null 84 } 85 86 // Perform arithmetic computations and display the results 87 performcomputations 88 TDisplay.setText(composeDisplayString 89 } 90 91 // Method to perform arithmetic computations 92 public void performcomputations() { Page 2
Printing C:\Documents and Settings\jgneal\My Documents\MyDev\MyJava\Exceptions\ExceptionExs\src\exceptionexs\NumberFormatEx.java a 98 } 99 100 // Method to compose the string for displaying computation results 101 public String composedisplaystring() { 102 return "First integer: " + int1 + "\nsecond integer: " + int2 + 103 "\n\nsum: " + sum + "\ndifference: " + difference + 104 "\nproduct: " + product + 106 } 107 } Page 3
Throwing an Exception A throws clause is needed in order for a method to throw an exception: returntype methodname(... ) throws ex1, ex2, ex3 { // Method body } The throw point: Place in method body at which throw is executed A throw statement is used to indicate when an exception has occurred (i.e., a method could not complete successfully) Errors and RuntimeExceptions can be thrown from almost any method and need not be listed in the throws clause These unlisted items are called unchecked All other exceptions that a method can throw must be listed in the method s throws clause These listed items are called checked 19 Example Program Purpose: To demonstrate How to define a new exception class (type) for a particular situation How to define a method that checks for certain error conditions (invalid entry of integer data) and throws the new exception type when error conditions occur Program: Project: ExceptionsExs Package: exceptionexs File: ExceptionDemo.java Questions: See next slide 20
Questions: Example Program Can the program detect which text field was the source of error? If so, how can the program report which text field it was? If the user does not enter anything in one of the text fields, an exception is thrown. How can the program intercept this and provide a better message to the user? (continued on next slide) 21 Exception Program Example 22
Printing C:\Documents and Settings\jgneal\My Documents\MyDev\MyJava\Exceptions\ExceptionExs\src\exceptionexs\ExceptionDemo.java at 1 // Purpose: Provide an example of a programmer-defined exception class, 2 // MyConvertException, and a programmer-defined method that 3 // throws an exception 4 package 5 import 6 import 7 import 8 import 9 10 public class ExceptionDemo extends JFrame implements ActionListener { 11 // Instance variables 12 private // Mechanisms to get user input 13 private int // The integers from user 14 15 private // Output display area 16 private int // Width of the JTextArea 17 private int // Height of the JTextArea 18 19 // The main method required for an application program 20 public static void main( String[] args ) { 21 JFrame frame = new ExceptionDemo // Construct the window 22 frame.setsize( new Dimension // Set its size 23 frame.setdefaultcloseoperation 24 frame.setvisible( true // Make the window visible 25 } 26 27 // Constructor 28 public ExceptionDemo () { 29 super 30 Container c = getcontentpane 31 c.setlayout( new BorderLayout 32 33 JPanel jpan = new JPanel 34 jpan.setborder(new EtchedBorder 35 Box box = Box.createVerticalBox 36 37 JLabel prompt1 = new JLabel("Enter two integers, then hit the Enter key:", 39 input1 = new JTextField 40 input2 = new JTextField 41 42 box.add 43 box.add 44 box.add 45 jpan.add 46 c.add 47 Page 1
Printing C:\Documents and Settings\jgneal\My Documents\MyDev\MyJava\Exceptions\ExceptionExs\src\exceptionexs\ExceptionDemo.java at 48 // Create and display a text area for presenting results 49 TDisplay = new JTextArea( composedisplaystring(), 51 TDisplay.setBorder(new EtchedBorder 52 TDisplay.setLineWrap( true 53 TDisplay.setWrapStyleWord( true 54 TDisplay.setEditable(false 55 c.add 56 57 // "this" window will respond to user input in text field 58 input1.addactionlistener ( this 59 input2.addactionlistener ( this 60 } 61 62 // Process user's action in JTextField 63 public void actionperformed ( ActionEvent e) { 64 // Get the string data from the JTextFields 65 String numbstr1 = input1.gettext 66 String numbstr2 = input2.gettext 67 68 try { // Convert input from type String to type int 69 int1 = converttointeger 70 int2 = converttointeger 71 } 72 catch( MyConvertException ex ) { 73 String msg = "Catch block parameter matches MyConvertException\n" + ex.tostring 74 JOptionPane.showMessageDialog( 75 null 76 return 77 } 78 catch ( Exception ex ) { 79 String msg = "Catch block parameter matches Exception\n" + ex. tostring 80 JOptionPane.showMessageDialog( 81 null 82 return 83 } 84 // Display the results 85 TDisplay.setText(composeDisplayString 86 input1.settext 87 input2.settext 88 } 89 90 exception 91 public int converttointeger( String str ) throws MyConvertException, MyEmptyStringException { Page 2
Printing C:\Documents and Settings\jgneal\My Documents\MyDev\MyJava\Exceptions\ExceptionExs\src\exceptionexs\ExceptionDemo.java at 92 int // Hold the integer version of converted char 93 char // Hold the character extracted from text field string 95 96 if (str.length() == 0) 97 throw new MyEmptyStringException 98 99 char sign = str.charat 100 if ( sign == '-' ) 101 tempstr = tempstr.substring 102 103 for ( int length 104 ch = tempstr.charat 105 if (!Character.isDigit(ch) ) { 106 throw new MyConvertException 107 } 108 } 109 return Integer.parseInt 110 } 111 112 // Method to compose the text for displaying results 113 public String composedisplaystring() { 114 return "First integer entered: " + int1 + 115 "\nsecond integer entered: " + int2 + 116 "\n\nsum = " + (int1+int2) + 118 } 119 } 120 121 // Purpose: Exception indicating that the input data is not valid 122 class MyConvertException extends Exception { 123 // Constructor 124 MyConvertException(int pos, char ch) { 125 super("the input contains invalid character " + ch + " at position 126 } 127 } 128 129 // Purpose: Exception indicating that the input data is not valid 130 class MyEmptyStringException extends Exception { 131 // Constructor 132 MyEmptyStringException() { 133 super 134 } 135 } Page 3