computer science ii for majors
play

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


  1. CMSC202 Computer Science II for Majors Lecture 16 – Exceptions Dr. Katherine Gibson www.umbc.edu

  2. Last Class We Covered • Inheritance • Polymorphism • Virtual functions – Abstract Classes • Exam 2 2 www.umbc.edu

  3. Any Questions from Last Time? www.umbc.edu

  4. Today’s Objectives • Error handling • Exceptions • Defining exception classes • Using exceptions – Try – Throw – Catch • When to throw exceptions 4 www.umbc.edu

  5. Error Handling www.umbc.edu

  6. 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 www.umbc.edu

  7. 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 www.umbc.edu

  8. 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 original coder decided would be best 8 www.umbc.edu

  9. 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 www.umbc.edu

  10. 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 www.umbc.edu

  11. Exceptions www.umbc.edu

  12. 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 www.umbc.edu

  13. Try / Throw / Catch • Exceptions are implemented using the keywords try, throw, and catch 13 www.umbc.edu

  14. 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 www.umbc.edu

  15. 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 www.umbc.edu

  16. 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 www.umbc.edu

  17. Exception Example // inside SetCarID() function if (newID < MIN_ID_VAL || newID > MAX_ID_VAL) { cerr << "ID invalid, no change"; } 17 www.umbc.edu

  18. Exception Example // inside SetCarID() function try { if (newID < MIN_ID_VAL || newID > MAX_ID_VAL) { cerr << "ID invalid, no change"; } } catch () { } 18 www.umbc.edu

  19. Exception Example // inside SetCarID() function try { if (newID < MIN_ID_VAL || newID > MAX_ID_VAL) { throw(newID); } } catch () { } 19 www.umbc.edu

  20. Exception Example // inside SetCarID() function try { if (newID < MIN_ID_VAL || newID > MAX_ID_VAL) { throw(newID); } } catch (int ID) { } 20 www.umbc.edu

  21. 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 www.umbc.edu

  22. Catching and Throwing www.umbc.edu

  23. 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 www.umbc.edu

  24. Using Catch • You can throw from inside a catch block • But this should be done sparingly and only 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 www.umbc.edu

  25. 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 www.umbc.edu

  26. 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 www.umbc.edu

  27. 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 www.umbc.edu

  28. 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 www.umbc.edu

  29. Throw List Example: Inside void SetCarID(int newID) throw (int) { if (newID < MIN_ID_VAL || newID > MAX_ID_VAL) { throw(newID); this function might } throw an integer else { m_carID = newID; } } 29 www.umbc.edu

  30. 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 www.umbc.edu

  31. Throw List Example: Outside v1 // inside main() try { train.at(0).SetCarID(-1); } catch (int ID) { cerr << "ID invalid, no change"; } this user has based their code on getting input from a file 31 www.umbc.edu

  32. Throw List Example: Outside v2 // inside main() this user has based their code on getting input while(set == false) { from a user, and being try { able to repeat requests train.at(0).SetCarID(userID); set = true; } catch (int ID) { cerr << "ID" << ID << "invalid, give another"; cin >> userID; } 32 } www.umbc.edu

  33. Exception Classes www.umbc.edu

  34. 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 www.umbc.edu

  35. Exception Class Example class MathError { /*...*/ }; class DivideByZeroError: public MathError { /*...*/ }; class InvalidNegativeError: public MathError { /*...*/ }; 35 www.umbc.edu

  36. 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 www.umbc.edu

  37. Nested Functions? // function2 throws an exception // main calls function1, void function2( ) // with try/catch { int main( ) cout << "function2" << endl; { throw int(42); try { } function1( ); } // function1 calls function2, catch (int) // but with no try/catch { void function1( ) cout << "Exception" { << "occurred" function2( ); << endl; cout << "function1" << endl; } } return 0; } What Stack is unwound until What happens something catches the exception happens here? OR until unwinding passes main then? 37 www.umbc.edu

  38. 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( ); } www.umbc.edu

  39. 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 www.umbc.edu

  40. Announcements • Project 4 is out! • We’ll go over Exam 2 next time 40 www.umbc.edu

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend