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 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 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 ExceptionDescription ArithmeticExceptionArithmetic error, such as divide-by-zero. ArrayIndexOutOfBoundsExceptionArray index is out-of-bounds. ArrayStoreExceptionAssignment to an array element of an incompatible type. ClassCastExceptionInvalid cast. IllegalArgumentExceptionIllegal argument used to invoke a method. IllegalMonitorStateExceptionIllegal monitor operation, such as waiting on an unlocked thread. IllegalStateExceptionEnvironment or application is in incorrect state. IllegalThreadStateExceptionRequested operation not compatible with current thread state. IndexOutOfBoundsExceptionSome type of index is out-of-bounds. NegativeArraySizeExceptionArray created with a negative size. NullPointerExceptionInvalid use of a null reference. NumberFormatExceptionInvalid conversion of a string to a numeric format. SecurityExceptionAttempt to violate security. StringIndexOutOfBoundsAttempt to index outside the bounds of a string. UnsupportedOperationExceptionAn 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 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 Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program.
13 Runtime Exceptions 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 throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); }
15 Catching Exceptions try { 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
17 Trace a Program Execution animation try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; Suppose no exceptions in the statements
18 Trace a Program Execution animation try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; The final block is always executed
19 Trace a Program Execution animation try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; Next statement in the method is executed
20 Trace a Program Execution animation 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 Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The exception is handled.
22 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The final block is always executed.
23 Trace a Program Execution animation 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 Execution animation 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 Execution animation 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 Execution animation 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 Execution animation 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