27
CHAPTER 5 EXCEPTION HANDLING Programming in C++ 1

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

Embed Size (px)

Citation preview

Page 1: 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

CHAPTER 5 EXCEPTION HANDLING

Programming in C++

1

Page 2: 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

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

Page 3: 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

3

Exception-Handling Overview

What do you think if 4 divided by 0?

Page 4: 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

Exception-Handling Overview

It is possible C++ can calculate this equation?

4

Page 5: 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

Exception-Handling Overview

C++ cannot calculate that equation, the output will be failed!!

5

Page 6: 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

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;}

Page 7: 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

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.

Page 8: 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

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

Page 9: 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

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

Page 10: 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

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

Page 11: 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

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.

Page 12: 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

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.

Page 13: 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

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.

Page 14: 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

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"); }

Page 15: 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

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;}

Page 16: 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

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

Page 17: 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

17

Trace a Program Executionanimation

try { statements;}catch(TheException ex) { handling ex; }finally { finalStatements; }

Next statement;

Suppose no exceptions in the statements

Page 18: 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

18

Trace a Program Executionanimation

try { statements;}catch(TheException ex) { handling ex; }finally { finalStatements; }

Next statement;

The final block is always executed

Page 19: 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

19

Trace a Program Executionanimation

try { statements;}catch(TheException ex) { handling ex; }finally { finalStatements; }

Next statement;

Next statement in the method is executed

Page 20: 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

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

Page 21: 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

21

Trace a Program Executionanimation

try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }

Next statement;

The exception is handled.

Page 22: 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

22

Trace a Program Executionanimation

try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }

Next statement;

The final block is always executed.

Page 23: 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

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.

Page 24: 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

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.

Page 25: 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

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

Page 26: 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

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

Page 27: 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

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