Oop Lab - 12
Oop Lab - 12
Oop Lab - 12
LAB 12
Summary
Items Description
Course Title Object Oriented Programming
Duration 3 Hours
Objectives
To catch exceptions we must place a portion of code under exception inspection. This is
done by enclosing that portion of code in a try block. When an exceptional circumstance
arises within that block, an exception is thrown that transfers the control to the exception
handler. If no exception is thrown, the code continues normally and all handlers are
ignored.
An exception is thrown by using the throw keyword from inside the try block. Exception
handlers are declared with the keyword catch, which must be placed immediately after
the try block.
Example 13.1
// exceptions
#include <iostream>
using namespace std;
int main () {
try
{
throw 20;
}
catch (int e)
{
cout << "An exception occurred. Exception Nr. " << e << endl;
}
return 0;
}
Output:
An exception occurred. Exception Nr. 20
The code under exception handling is enclosed in a try block. In this example this code
simply throws an exception:
FATIMA JINNAH WOMEN UNIVERSITY
Department Of Software Engineering
throw 20;
A throw expression accepts one parameter (in this case the integer value 20), which is
passed as an argument to the exception handler.
The exception handler is declared with the catch keyword. As you can see, it follows
immediately the closing brace of the try block. The catch format is similar to a regular
function that always has at least one parameter. The type of this parameter is very
important, since the type of the argument passed by the throw expression is checked
against it, and only in the case they match, the exception is caught.
We can chain multiple handlers (catch expressions), each one with a different
parameter type. Only the handler that matches its type with the argument specified in
the throw statement is executed.
If we use an ellipsis (...) as the parameter of catch, that handler will catch any exception
no matter what the type of the throw exception is. This can be used as a default handler
that catches all exceptions not caught by other handlers if it is specified at last:
try {
// code here
}
catch (int param) { cout << "int exception"; }
catch (char param) { cout << "char exception"; }
catch (...) { cout << "default exception"; }
In this case the last handler would catch any exception thrown with any parameter that
is neither an int nor a char.
After an exception has been handled the program execution resumes after the try-catch
block, not after the throw statement!.
FATIMA JINNAH WOMEN UNIVERSITY
Department Of Software Engineering
It is also possible to nest try-catch blocks within more external try blocks. In these
cases, we have the possibility that an internal catch block forwards the exception to its
external level. This is done with the expression throw; with no arguments. For example:
try {
try {
// code here
}
catch (int n) {
throw;
}
}
catch (...) {
cout << "Exception occurred";
}
You can also create a class to handle exceptions thrown by other classes. Below is the
general syntax illustrating an exception handler.
public:
};
}
FATIMA JINNAH WOMEN UNIVERSITY
Department Of Software Engineering
};
Example 12.1
The following example illustrates throwing and catching exceptions from the Stack
class.
int pop()
{
if(top < 0) //if stack empty,
throw Range(); //throw exception
return st[top--]; //take number off stack
}
};
void main()
{
Stack s1;
try
{
s1.push(11);
s1.push(22);
s1.push(33);
s1.push(44); //stack full
In the above example, the Range class is handling the exceptions thrown when the
stack is either empty or full. We could perfectly define two separate classes to handle
the exceptions of each type.
Example 12.2
FATIMA JINNAH WOMEN UNIVERSITY
Department Of Software Engineering
//---------------------------------------------------
void main()
{
Stack s1;
try
{
s1.push(11);
s1.push(22);
s1.push(33);
s1.push(44);
cout << "1: " << s1.pop() << endl;
cout << "2: " << s1.pop() << endl;
cout << "3: " << s1.pop() << endl;
cout << "4: " << s1.pop() << endl;
FATIMA JINNAH WOMEN UNIVERSITY
Department Of Software Engineering
}
catch(Stack::Full)
{ cout << "Exception: Stack Full” << endl; }
catch(Stack::Empty)
{ cout << "Exception: Stack Empty” << endl; }
getch();
}
In the above examples, the exception classes we created were empty. It is also possible
to have more useful exception classes with data members to store information about the
origin and source of exception for example. The following example illustrates this idea
for the Distance class.
Example 12.3
class Distance
{
private:
int feet;
float inches;
public:
class InchesEx //exception class
{
public:
char origin[20];
float iValue;
InchesEx(string or, float in)
{
strcpy(origin,or.c_str());
FATIMA JINNAH WOMEN UNIVERSITY
Department Of Software Engineering
iValue = in;
}
}; //end of exception class
void main()
{
try
{
Distance dist1(17, 3.5);
Distance dist2;
dist2.getdist();
cout << "\ndist1 = "; dist1.showdist();
cout << "\ndist2 = "; dist2.showdist();
}
catch(Distance::InchesEx ix) //exception handler
{
cout << "\nInitialization error in " << ix.origin <<
".\n Inches value of " << ix.iValue << " is too large.";
}
cout << endl;
getch();
}
FATIMA JINNAH WOMEN UNIVERSITY
Department Of Software Engineering
LAB TASKS
Exercise 1
Create a class Student with data members age and marks, both of type integer. Provide a
parameterized constructor and a set member function to set the data members. The age should be
a positive number between 15 and 40 while the marks should be between 0 and 100. Create a class
InvalidRange as exception handler of the Student class. The student class should throw an
exception if any of its member functions attempts to assign an invalid value to the data members.
In the main program, create objects of class student, assign valid/invalid values to the data
members and catch the exceptions accordingly.
Exercise 2
Modify the above program to add two private data members (a string and an integer) to the class
InvalidRange. Provide appropriate constructor and get methods for the data members. The string
should store the name of the function throwing the exception while the integer should store the
invalid value the user has supplied.
Exercise 3
Extend the program in Exercise 2 to have two separate classes for exception handling,
InvalidMarks and InvalidAge.