CS210 Lab: Stacks--Exception Handling


Overview:

What is an Exception?

How do you handle an Exception?

Use try-catch and throw statements.

Throw Statement

To throw (or raise) an exception, the programmer uses a throw statement, whose syntax is as follows:
	throw Expession;
Specifically, in this lab (in StackType.cpp) two exceptions are thrown:
	throw FullStack();
and
	throw EmptyStack();
Notice, that these are both "exception classes" which have been defined in StackType.h:
class FullStack
// Exception class thrown by Push when stack is full.
{};

class EmptyStack
// Exception class thrown by Pop and Top when stack is emtpy.
{};

Try-Catch Statement

If one part of a program throws an exception, another part should catch the exception and process it. This is done with the try-catch statement.

The general syntax of a try-catch statement is as follows:

try
  Block
catch ( FormalParameter ) 
  Block
catch ( FormalParameter ) 
  Block
	.
	.
	.

In other words, the syntax is a try clause followed by one or more catch clauses. The "Block" may be any number of statements enclosed by a pair of {}.

When a statement or group of statements might result in an exception, we enclose them in a try clause. For each type of exception that can be produced by the statements in the try clause, we write a catch clause (exception handler).

Make sure that all exceptions are caught. An uncaught exception results in program termination with an error message.

Example Code of Try-Catch and Throw

The following is a complete code which shows how you can put Try-Catch and Throw together:
#include <iostream>
#include <string>

using namespace std;

int Dividing( int, int);

class ZeroDiv // Exception class
{};

int main()
{
	int num; // Numerator
	int num2; //Denominator

	cout << "Enter numerator and denominator:";
	cin >> num >> num2;
	
	try
	{
		cout<< "Their quotient: "
		    << Dividing(num, num2) << endl;
	}
	catch (ZeroDiv)
	{
		cout << "Can't divide by zero" << endl;
	}
	return 0;
}
int Dividing(int num, int num2)
{
	if (num2==0)
		throw ZeroDiv();
	return num/num2;
}

Lab Specific Hints

The only file that you will modify is Balanced.cpp
  1. Add a try clause
  2. Add a catch clause for FullStack
  3. For completeness, add a catch clause for EmptyStack (optional)

Back to Stack Lab click here

CS Dept Home Page
CS Dept Class Files
CS210 Class Files

Copyright: Department of Computer Science, University of Regina.