Previous Lecture Lecture 11 Next Lecture

Lecture 11, Wed 02/19

Exceptions

Exceptions

Example

int main() {
	int value;
	try {
		cout << "Enter a positive number: ";
		cin >> value;

		if (value < 0)
			throw value;

		cout << "The number entered is: " << value << endl;
	} catch (int e) {
		cout << "The number entered is not positive." << endl;
	}
	
	cout << "Statement after try/catch block" << endl;
	return 0;
}
int main() {
    int value;
    try {
        try {
            cout << "in try block within try block" << endl;
            throw 100;
        } catch (int d) {
            cout << "In catch block within try block: " << d << endl;
        }
        cout << "Enter a positive number: ";
        cin >> value;

        if (value < 0)
            throw value;

        cout << "The number entered is: " << value << endl;
    } catch (int e) {
        cout << "The number entered is not positive." << endl;
        try {
            cout << "In try block within catch" << endl;
            string message = "some error message";
            throw message;
        } catch (string s) {
            cout << "in catch block within catch block:" << s << endl;
        }
        cout << "exiting catch (int e) block" << endl;
    }
	
    cout << "Statement after try/catch block" << endl;
    return 0;
}

Throwing / Catching Multiple Exceptions

Example

class NegativeValueException {};
class EvenValueException {};

// …
if (value < 0)
	throw NegativeValueException();
if (value % 2 == 0)
	throw EvenValueException();
// …

catch(NegativeValueException e) {
	cout << "The number entered is not positive." << endl;
} catch (EvenValueException e) {
	cout << "The number entered is even." << endl;
}

Another Example

class DivideByZeroException {};

// Note that the throw (DivideByZeroException) is not required
// since C++ does not support "checked" exceptions.
double divide(int numerator, int denominator) throw (DivideByZeroException) {
	if (denominator == 0)
		throw DivideByZeroException();
	return numerator / (double) denominator;
}

int main() {
	try {
		cout << divide(1,1) << endl;
		cout << divide(1,0) << endl;
		cout << divide(2,2) << endl;
	} catch (DivideByZeroException) { // variable name is optional
		cout << "Error: cannot divide by zero" << endl;
	}
}

Inheritance and Exceptions

Example:

class A {};
class B : public A {};
class C {};

int main() {
	int value;
	try {
		cout << "Enter a positive number: ";
		cin >> value;
	
		if (value < 0)
			throw B();
	} catch (C) {
		cout << "Exception of type C caught." << endl;
	} catch (A) {
		cout << "Exception of type A caught." << endl;
	} catch (B) {
		cout << "Exception of type B caught." << endl;
	}
	return 0;
}

Note: Exceptions are checked top-to-bottom. The compiler may provide a warning if A exists before B since an exception of type B will never get caught if thrown in this case.