csc 270 – survey of programming languages c++ lecture 6 – exceptions
TRANSCRIPT
CSC 270 – Survey of Programming Languages
C++ Lecture 6 – Exceptions
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 <stdexcept>
• Can use an error class that exists instead
ExceptionDemo.cpp creation of the Error classes
#include <iostream>#include <string>using namespace std;
class NegativeNumber {public:
NegativeNumber(void) {}NegativeNumber(string theMessage)
: message(theMessage) {}string getMessage() const {return message; }
private:string message;
};class DivideByZero {};
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.
int main(void){
int pencils, erasers;double ppe; //pencils per eraser
try {cout << "How many pencils do you"
<< " have?\n";cin >> pencils;if (pencils < 0)
throw NegativeNumber("pencils");
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
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;
}
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);