Upload
clifford-baldwin
View
218
Download
0
Embed Size (px)
Citation preview
ExceptionsChapter 16
This chapter explains:What as exception isWhy they are useful
Java exception facilities
An exception = something has gone wrong – an error has occurred – not a good thing
• Examples: the use was asked to input a size (numeric) and put in a name (string)
• The program could:– Quit and return to the operating system– Ignore the input– Display a help message
Another example: an attempt to load a file
• It cannot be found (possible responses – same as last example)
• Attempt to print and out of paper– Some printer software examines the status
and will indicate out of paper condition
Why do we need error notification? How is it provided?
• Software and hardware systems in Java are pre-packaged (classes and methods) we don’t care how they work internally – but – vital we are informed of error conditions
• Software may be set up to detect errors and take alternative action. Some errors handled locally – more serious are passed “upstairs.”
A printer runs out of paper…
• Normally a technician refills the printer but what if the organization is out – a manager may need to be informed.
• A technician trips on a cable and breaks a leg (possible legal action) Should be handled by a managing director.
• Analogy: a person doing a job and a method when a error occurs. Java exception facilities allow us to set up a plan of action.
• If something wrong – handle the problem else handle the normal situation.
Given: do A(); do B(); do C();
• Becomes:– do A();
• if ( do A() went wrong) handle the do A() problem
– else do B();– if ( do B() went wrong) handle the do B()
problem– else do C();
• if ( do C() went wrong) handle the do C() problem
– else …
If an error condition occurs (we do not want it to occur) Java exception
facilities allow us to code the normal and the exceptional use
• Java methods can only pass back a single result
Exceptions and objects
• Boolean variables are not always the answer as to when an error occurs:
• boolean errorhappened = false;
• … code whichaffects errorCase– if (errorHappened = = true ) {– … handle problem …
This is not how errors are indicated by Java
• We use the object approach. We use ‘new’ to create an instance of the appropriate exception class.
• Another region of the program may check for the errors existance
• An instance of the exception class is created to indicate “an error happened”
When to use exceptions
• Exceptions provide a control structure– When should we use them? Rather than an if
statement or while loop.
• Example: we wish to add a series of positive numbers and end the series with a -1. That is not the exception. (it is normal input) We use exception handling for errors not normal input.
The jargon of exceptions – Java’s own terminology
• throws, throw, try, catch and finally are keywords that carry out the task or error detection.
• A try – catch example program: ExceptionDemo1 pages 300-301. “a number doubling program”
• User inputs an integerr and program doubles it and displays the answer in another field. If the user inputs something ‘not a number’ the ‘parseInt method will not be able to process it.
• Screen shot page 302 shows ‘good’ integer and doubles it. ‘bad’ integer ‘xx’ blanks the output field and error message
Key part of program
• try {int number = Integer.parseInt (inputField.setText (Integer.toString( 2 * number))
• } catch (Number FormatException errorObject) { JOptionPane.showMessageDialog (null, “Error in number retype” ); }
The ‘new’ statement: general form
• try { a series of statements }
• cach (some exception errorObject) { handle the exception;}
• A Java block { } all statement within curly braces
• Execute statements in the try block if no error catch block ignored. If error occurs catch block is executed.
• catch (NumberFormatException errorObject) similar to a methos declaration.
• parseInt may throw a NumberFormatException if it does catch block will execute.– Catch (NumberFormatException errorObject)
{ OPtionPane.showMessageDialog (null, “Error “ + errorObject.toString ( ) );}
– // returns the name of the exception
• private void aMethod ( ) {– try { // some code …}– catch (Exception errorObject) {handle it}– return
try and scope
• When a try block produces an exception – execution terminates – variables declared within it become inaccessible (can not be used in catch block) They must be declared outside the try block
• String s;
• try { code involving s…}
• catch (exception errorObject) {– JOptionPane.showMessageDialog ( null ,
“Error: s is “ + s);}