lecture38-may3 - Lecture 38 Announcements Assignment 7...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
1 Lecture 38 Announcements • Assignment 7 Program due Friday; Q&A • Exam 3 on Wednesday in class No final during finals week Exams back in lecture on Friday, course evals, + more • Topics of the day – – More writing fault tolerant programs – Exceptions – mostly not in the book (~Ch 24.1-2) • Review for exam 3 Exception Handling Example // this example illustrates prevention of a divide by zero error #include <iostream> using namespace std; double divide(double, double); int main() { double x, y, z; cout << "Enter numerator followed by denominator: "; cin >> x >> y; z = divide(x, y); //gracefully handle divide by zero return 0; } double divide(double a, double b) { try { if (b = = 0.0) throw b; // check for divide-by-zero return a / b; } catch (double b) { cout << "Can't divide by zero.” << endl; } return 0.0; } Exceptions - example 2 #include <math.h> // for sqrt() function #include <string> #include <iostream> using namespace std; int main() { bool flag = true; while (flag) { cout << "Enter a positive real number: "; double dX; cin >> dX; try // Look for exceptions occuring within try block,route to attached catch block(s) { // If the user entered a negative number, this is an error condition if (dX < 0.0) throw "Can not take sqrt of negative number"; // throw exception of type string // Otherwise, print the answer and exit loop else {cout << "The sqrt of " << dX << " is " << sqrt(dX) << endl; flag = false;} } catch (string strException) // catch exceptions of type string { cerr << "Error: " << strException << endl; } } return 0; } Purpose: take the square root of a given positive real number.
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 3

lecture38-may3 - Lecture 38 Announcements Assignment 7...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online