Computer Science II for Majors Lecture 16 Exceptions Dr. Katherine - - PowerPoint PPT Presentation

computer science ii for majors
SMART_READER_LITE
LIVE PREVIEW

Computer Science II for Majors Lecture 16 Exceptions Dr. Katherine - - PowerPoint PPT Presentation

CMSC202 Computer Science II for Majors Lecture 16 Exceptions Dr. Katherine Gibson www.umbc.edu Last Class We Covered Inheritance Polymorphism Virtual functions Abstract Classes Exam 2 2 www.umbc.edu Any Questions from


slide-1
SLIDE 1

www.umbc.edu

CMSC202 Computer Science II for Majors

Lecture 16 –

Exceptions

  • Dr. Katherine Gibson
slide-2
SLIDE 2

www.umbc.edu

Last Class We Covered

  • Inheritance
  • Polymorphism
  • Virtual functions

– Abstract Classes

  • Exam 2

2

slide-3
SLIDE 3

www.umbc.edu

Any Questions from Last Time?

slide-4
SLIDE 4

www.umbc.edu

Today’s Objectives

  • Error handling
  • Exceptions
  • Defining exception classes
  • Using exceptions

–Try –Throw –Catch

  • When to throw exceptions

4

slide-5
SLIDE 5

www.umbc.edu

Error Handling

slide-6
SLIDE 6

www.umbc.edu

Common Errors

  • We have seen a number of error types:

– Could not allocate memory – Out-of-bounds on vector – File not found/could not be opened – Attempting to add a train car that’s not allowed – A poker hand with invalid cards

6

slide-7
SLIDE 7

www.umbc.edu

Handling Errors – Now

  • How are these errors handled?

–Print a message

  • “You cannot add a second Snack Car”

–Do nothing –Exit the program

  • The errors are handled right where they occur

7

slide-8
SLIDE 8

www.umbc.edu

Handling Errors at Occurence

  • Advantages:

– Easy to find because code is right there

  • Disadvantages:

– Error handling scattered throughout code – Code duplication – Code inconsistency (even worse!) – Errors are handled however the

  • riginal coder decided would be best

8

slide-9
SLIDE 9

www.umbc.edu

Two “Coders” for Each Class

  • Class implementer

– Creates the class definition – Knows what constitutes an error – Decides how to handle errors

  • Class user

– Uses the class implementation – Knows how they want to handle errors

  • (But if handled internally, the class user

may not even know an error occurred)

9

slide-10
SLIDE 10

www.umbc.edu

Separating Errors

  • Want to separate errors into two pieces:

–Error detection

  • Implementer knows how to detect

–Error handling

  • User can decide how to handle
  • Use exceptions to do this

10

slide-11
SLIDE 11

www.umbc.edu

Exceptions

slide-12
SLIDE 12

www.umbc.edu

Exceptional Cases

  • Exceptions are used to handle exceptional cases

– Cases that shouldn’t occur normally

  • Allow us to indicate an error has occurred

without explicitly handling it

– C++ uses these too, like when we try to use .at() to examine an out-of-bounds element

12

slide-13
SLIDE 13

www.umbc.edu

Try / Throw / Catch

  • Exceptions are implemented using the

keywords try, throw, and catch

13

slide-14
SLIDE 14

www.umbc.edu

Try / Throw / Catch

  • Exceptions are implemented using the

keywords try, throw, and catch

  • The try keyword means we are going to try

something, even though we are not sure it is going to perform correctly

14

slide-15
SLIDE 15

www.umbc.edu

Try / Throw / Catch

  • Exceptions are implemented using the

keywords try, throw, and catch

  • The throw keyword is used when we

encounter an error

  • Means we are going to “throw” two things

– A value (explicit) – Control flow (implicit)

15

slide-16
SLIDE 16

www.umbc.edu

Try / Throw / Catch

  • Exceptions are implemented using the

keywords try, throw, and catch

  • The catch keyword means we are going to

try to catch at most one type of value

– To catch different types of values, we need multiple catch statements

16

slide-17
SLIDE 17

www.umbc.edu

Exception Example

// inside SetCarID() function if (newID < MIN_ID_VAL || newID > MAX_ID_VAL) { cerr << "ID invalid, no change"; }

17

slide-18
SLIDE 18

www.umbc.edu

Exception Example

// inside SetCarID() function try { if (newID < MIN_ID_VAL || newID > MAX_ID_VAL) { cerr << "ID invalid, no change"; } } catch () { }

18

slide-19
SLIDE 19

www.umbc.edu

Exception Example

// inside SetCarID() function try { if (newID < MIN_ID_VAL || newID > MAX_ID_VAL) { throw(newID); } } catch () { }

19

slide-20
SLIDE 20

www.umbc.edu

Exception Example

// inside SetCarID() function try { if (newID < MIN_ID_VAL || newID > MAX_ID_VAL) { throw(newID); } } catch (int ID) { }

20

slide-21
SLIDE 21

www.umbc.edu

Exception Example

// inside SetCarID() function try { if (newID < MIN_ID_VAL || newID > MAX_ID_VAL) { throw(newID); } } catch (int ID) { cerr << "ID invalid, no change"; }

21

slide-22
SLIDE 22

www.umbc.edu

Catching and Throwing

slide-23
SLIDE 23

www.umbc.edu

Using Catch

  • The catch keyword requires:

– One parameter

  • Typename (int, exception, out_of_range, etc)
  • Name (newID, e, oor, etc.) [optional]
  • To catch multiple types of exceptions, you

need to use multiple catch blocks

23

slide-24
SLIDE 24

www.umbc.edu

Using Catch

  • You can throw from inside a catch block
  • But this should be done sparingly and
  • nly after careful consideration

– Most of the time, a nested try-catch means you should re-evaluate your program design

  • Uncaught exceptions will cause the

terminate() function to be called

24

slide-25
SLIDE 25

www.umbc.edu

Using Catch

  • Catch blocks are run in order, so exceptions

should be caught in order from –Most specific to least specific

  • To catch all possible exceptions, use:

catch(...)

  • (Literally use three periods as a parameter)

25

slide-26
SLIDE 26

www.umbc.edu

Throwing Out of a Function

  • We can throw exceptions without try/catch

– Most commonly done within functions

  • Requires that we list possible exception types

in the function prototype and definition

– Called a throw list

26

slide-27
SLIDE 27

www.umbc.edu

Throw Lists

  • Warn programmers that functions throw

exceptions without catching them

  • Throw lists should match up with what is

thrown and not caught inside the function

– Otherwise, it can lead to a variety of errors, including the function unexpected()

  • Can also have empty throw lists for clarity:

int GetCarID() throw ();

27

slide-28
SLIDE 28

www.umbc.edu

Throw List Syntax

  • Functions can specify their throw lists

// Throws only 1 type of exception retType funcName( params ) throw (excep); // Throws 2 types of exceptions (comma separated list) retType funcName( params ) throw (excep1, excep2); // Promises not to throw any exceptions retType funcName( params ) throw ( ); // Can throw any exceptions [backwards compatibility] retType funcName( params );

28

slide-29
SLIDE 29

www.umbc.edu

Throw List Example: Inside

void SetCarID(int newID) throw (int) { if (newID < MIN_ID_VAL || newID > MAX_ID_VAL) { throw(newID); } else { m_carID = newID; } }

29

this function might throw an integer

slide-30
SLIDE 30

www.umbc.edu

Throw List Example: Outside v0

// inside main() train.at(0).SetCarID(-1);

  • What will happen if we run this code?

– The exception won’t be caught – The terminate() function will be called

30

slide-31
SLIDE 31

www.umbc.edu

Throw List Example: Outside v1

// inside main() try { train.at(0).SetCarID(-1); } catch (int ID) { cerr << "ID invalid, no change"; }

31

this user has based their code

  • n getting input from a file
slide-32
SLIDE 32

www.umbc.edu

Throw List Example: Outside v2

// inside main() while(set == false) { try { train.at(0).SetCarID(userID); set = true; } catch (int ID) { cerr << "ID" << ID << "invalid, give another"; cin >> userID; } }

32

this user has based their code on getting input from a user, and being able to repeat requests

slide-33
SLIDE 33

www.umbc.edu

Exception Classes

slide-34
SLIDE 34

www.umbc.edu

Exception Classes

  • We can create, throw, and catch exception

classes that we have created

  • We can even create hierarchies of exception

classes using inheritance –Catching the parent class will also catch all child class exceptions

34

slide-35
SLIDE 35

www.umbc.edu

Exception Class Example

class MathError { /*...*/ }; class DivideByZeroError: public MathError { /*...*/ }; class InvalidNegativeError: public MathError { /*...*/ };

35

slide-36
SLIDE 36

www.umbc.edu

Creating Exception Classes

  • Name of class reflects the error

– Not the code that throws error

  • Contains basic information or a message

– Parameter value – Name of function that detected error – Description of error

  • Methods required

– Constructor (one or more) – Accessor (one or more)

36

slide-37
SLIDE 37

www.umbc.edu

Nested Functions?

37

// function2 throws an exception void function2( ) { cout << "function2" << endl; throw int(42); } // function1 calls function2, // but with no try/catch void function1( ) { function2( ); cout << "function1" << endl; } // main calls function1, // with try/catch int main( ) { try { function1( ); } catch (int) { cout << "Exception" << "occurred" << endl; } return 0; }

What happens here? Stack is unwound until something catches the exception OR until unwinding passes main What happens then?

slide-38
SLIDE 38

www.umbc.edu

Exceptions in Constructors

  • Best way to handle Constructor failure

– Replaces Zombie objects! – Any sub-objects that were successfully created are destroyed (destructor is not called!)

  • Example:

// MyClass constructor MyClass::MyClass ( int value ) { m_pValue = new int(value); // pretend something bad happened throw NotConstructed( ); }

slide-39
SLIDE 39

www.umbc.edu

Exceptions in Destructors

  • Bad, bad idea…

– What if your object is being destroyed in response to another exception?

  • Should runtime start handling your exception or the

previous one?

  • General Rule…

– Do not throw exceptions in destructor

slide-40
SLIDE 40

www.umbc.edu

Announcements

  • Project 4 is out!
  • We’ll go over Exam 2 next time

40