csc 270 – survey of programming languages c++ lecture 6 – exceptions

8
CSC 270 – Survey of Programming Languages C++ Lecture 6 – Exceptions

Upload: margaret-dixon

Post on 04-Jan-2016

216 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: CSC 270 – Survey of Programming Languages C++ Lecture 6 – Exceptions

CSC 270 – Survey of Programming Languages

C++ Lecture 6 – Exceptions

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

Page 3: CSC 270 – Survey of Programming Languages C++ Lecture 6 – Exceptions

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

Page 4: CSC 270 – Survey of Programming Languages C++ Lecture 6 – Exceptions

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.

Page 5: CSC 270 – Survey of Programming Languages C++ Lecture 6 – Exceptions

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

Page 6: CSC 270 – Survey of Programming Languages C++ Lecture 6 – Exceptions

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

Page 7: CSC 270 – Survey of Programming Languages C++ Lecture 6 – Exceptions

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;

}

Page 8: CSC 270 – Survey of Programming Languages C++ Lecture 6 – Exceptions

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