Previous Lecture Lecture 11 Next Lecture

Lecture 11, Thu 05/09

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

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

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.