Download presentation
Presentation is loading. Please wait.
Published byMargaret Dixon Modified over 9 years ago
1
CSC 270 – Survey of Programming Languages C++ Lecture 6 – Exceptions
2
Step 1: Create an error class Create a small class named as the error type If you inherit from runtime_error it will inherit a what method – Found in Can use an error class that exists instead
3
ExceptionDemo.cpp creation of the Error classes #include using namespace std; classNegativeNumber{ public: NegativeNumber(void) {} NegativeNumber(string theMessage) : message(theMessage) {} string getMessage() const {return message; } private: string message; }; class DivideByZero {};
4
Step 2: Throw when you find error Use the throw command Follow it by an object of an error class Throw will – Stop executing the method it is in – give that object back to the calling program If it is not caught, it will crash the program.
5
intmain(void) { intpencils, erasers; doubleppe;//pencils per eraser try{ cout << "How many pencils do you" << " have?\n"; cin >> pencils; if (pencils < 0) throw NegativeNumber("pencils");
6
Catch the error Surround the call to the method that may throw an error with a try { } After the try, add a catch block – Catch ( what you want to catch and its var name){ } Inside the catch block, you can access the variables inside the error object
7
cout << "How many erasers do you" << " have?\n"; cin >> erasers; if (erasers < 0) throw NegativeNumber("erasers"); if (erasers != 0) ppe = pencils / (double) erasers; else throw DivideByZero(); cout << "Each eraser must last through " << ppe << " pencils." << endl; }
8
catch(NegativeNumber e){ cout << "Cannot have a negative number of " << e.getMessage() << endl; } catch(DivideByZero){ cout << "Do not make any mistakes!" << endl; } cout << "End of program." << endl; return(0 );
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.