Upload
felicity-norman
View
212
Download
0
Tags:
Embed Size (px)
Citation preview
CHAPTER 5 EXCEPTION HANDLING
Programming in C++
1
Learning Outcome
At the end of this slide, student able to:
Identify the different types of error in your program Understand the different types of error handler clauses? Describe the usefulness of catch and finally statement in handling
exception? Understand the rethrowing exceptions
2
3
Exception-Handling Overview
What do you think if 4 divided by 0?
Exception-Handling Overview
It is possible C++ can calculate this equation?
4
Exception-Handling Overview
C++ cannot calculate that equation, the output will be failed!!
5
Exception Overview#include <iostream>
using namespace std;
const int DefaultSize = 10;
int main()
{
int top = 90;
int bottom = 0;
try
{
cout << "top / 2 = " << (top/ 2) << endl;
cout << "top divided by bottom = ";
if ( bottom == 0 )
throw "Division by zero!";
cout << (top / bottom) << endl;
cout << "top / 3 = " << (top/ 3) << endl;
}
catch( const char * ex )
{
cout << "\n*** " << ex << " ***" << endl;
}
cout << "Done." << endl;
return 0;
}
6
#include <iostream> using namespace std;
const int DefaultSize = 10;
int main(){ int top = 90; int bottom = 0;cout << "top / 2 = " << (top/ 2) << endl;
cout << "top divided by bottom = "; if ( bottom == 0 ){
cout << (top / bottom) << endl;// cout << "\n*** Division by zero! ***" << endl;}
else { cout << (top / bottom) << endl;
cout << "top / 3 = " << (top/ 3) << endl; }
cout << "Done." << endl; return 0;}
Example of Exception
7
Exception Description
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread.
IllegalStateException Environment or application is in incorrect state.
IllegalThreadStateException Requested operation not compatible with current thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
UnsupportedOperationException An unsupported operation was encountered.
Other Exception AWTException AclNotFoundException ActivationException AlreadyBoundException ApplicationException ArithmeticException ArrayIndexOutOfBoundsException AssertionException BackingStoreException BadAttributeValueExpException BadBinaryOpValueExpException BadLocationException BadStringOperationException BatchUpdateException BrokenBarrierException CertificateException ChangedCharSetException CharConversionException CharacterCodingException ClassCastException ClassNotFoundException CloneNotSupportedException ClosedChannelException ConcurrentModificationException DataFormatException
8
• DatatypeConfigurationException• DestroyFailedException• EOFException• Exception• ExecutionException• ExpandVetoException• FileLockInterruptionException• FileNotFoundException• FishFaceException• FontFormatException• GSSException• GeneralSecurityException• IIOException• IOException• IllegalAccessException• IllegalArgumentException• IllegalClassFormatException• IllegalStateException• IndexOutOfBoundsException • InputMismatchException• InstantiationException• InterruptedException• InterruptedIOException• IntrospectionException• InvalidApplicationException• InvalidMidiDataException• InvalidPreferencesFormatException• InvalidTargetObjectTypeException
InvocationTargetException JAXBException JMException KeySelectorException LastOwnerException LineUnavailableException MalformedURLException MarshalException MidiUnavailableException MimeTypeParseException NamingException NegativeArraySizeException NoSuchElementException NoSuchFieldException NoSuchMethodException NoninvertibleTransformException NotBoundException NotOwnerException NullPointerException NumberFormatException ObjectStreamException ParseException ParserConfigurationException PrintException PrinterException PrivilegedActionException PropertyVetoException
9
• ProtocolException• RefreshFailedException• RemarshalException• RemoteException• RuntimeException• SAXException• SOAPException• SQLException• SQLWarning• SSLException• ScriptException• ServerNotActiveException• SocketException• SyncFailedException• TimeoutException• TooManyListenersException• TransformException• TransformerException• URIReferenceException• URISyntaxException• UTFDataFormatException• UnknownHostException• UnknownServiceException• UnmodifiableClassException• UnsupportedAudioFileException• UnsupportedCallbackException• UnsupportedEncodingException• UnsupportedFlavorException• UnsupportedLookAndFeelException• UnsupportedOperationException• UserException• XAException• XMLParseException• XMLSignatureException• XMLStreamException• XPathException• ZipException
Friendly Advice about Exception
Actually, it is very difficult to remember all exception especially to junior programmer. However, the programmer can use online recourses.
10
11
System Errors
LinkageError
Error
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Many more classes
Many more classes
Many more classes
IllegalArgumentException
System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully.
12
Exceptions
LinkageError
Error
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Many more classes
Many more classes
Many more classes
IllegalArgumentException
Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program.
13
Runtime Exceptions
LinkageError
Error
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Many more classes
Many more classes
Many more classes
IllegalArgumentException
RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.
14
Throwing Exceptions Example
/** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); }
15
Catching Exceptionstry { statements; // Statements that may throw exceptions}catch (Exception1 exVar1) { handler for exception1;}catch (Exception2 exVar2) { handler for exception2;}...catch (ExceptionN exVar3) { handler for exceptionN;}
16
Catching Exceptions
main method { ... try { ... invoke method1; statement1; } catch (Exception1 ex1) { Process ex1; } statement2; }
method1 { ... try { ... invoke method2; statement3; } catch (Exception2 ex2) { Process ex2; } statement4; }
method2 { ... try { ... invoke method3; statement5; } catch (Exception3 ex3) { Process ex3; } statement6; }
An exception is thrown in method3
Call Stack
main method main method
method1
main method
method1
main method
method1
method2 method2
method3
17
Trace a Program Executionanimation
try { statements;}catch(TheException ex) { handling ex; }finally { finalStatements; }
Next statement;
Suppose no exceptions in the statements
18
Trace a Program Executionanimation
try { statements;}catch(TheException ex) { handling ex; }finally { finalStatements; }
Next statement;
The final block is always executed
19
Trace a Program Executionanimation
try { statements;}catch(TheException ex) { handling ex; }finally { finalStatements; }
Next statement;
Next statement in the method is executed
20
Trace a Program Executionanimation
try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }
Next statement;
Suppose an exception of type Exception1 is thrown in statement2
21
Trace a Program Executionanimation
try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }
Next statement;
The exception is handled.
22
Trace a Program Executionanimation
try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }
Next statement;
The final block is always executed.
23
Trace a Program Executionanimation
try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }
Next statement;
The next statement in the method is now executed.
24
Trace a Program Executionanimation
try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }catch(Exception2 ex) { handling ex; throw ex;}finally { finalStatements; }
Next statement;
statement2 throws an exception of type Exception2.
25
Trace a Program Executionanimation
try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }catch(Exception2 ex) { handling ex; throw ex;}finally { finalStatements; }
Next statement;
Handling exception
26
Trace a Program Executionanimation
try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }catch(Exception2 ex) { handling ex; throw ex;}finally { finalStatements; }
Next statement;
Execute the final block
27
Trace a Program Executionanimation
try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }catch(Exception2 ex) { handling ex; throw ex;}finally { finalStatements; }
Next statement;
Rethrow the exception and control is transferred to the caller