Lecture 12
Friends and
Exception Handling
Computer Programming II
Outlines
Friendship
Friend Function
Friend Class
Exception Handling
Exception
Exception Handler
try, throw and catch block
Exception Propagation
Multiple catch Blocks
Exception Matching
Advantages of Exception Handling
Computer Programming II
Friendship
Friendship allows a class to selectively grant
other function or class the access to its private
and protected members.
A friend function is a function that can access
private and protected members of a class, even
though the function itself is not a member of the
class.
A friend class is a class that can access private
and protected members of another class
Computer Programming II
Friendship
Friendship is granted. So for a function A or
class B to access the private and protected
members of class C, C must grant A and B the
friendship
Friendship is not automatically bi-directional.
When A makes B a friend, B does not
automatically make A a friend
Computer Programming II
Example: Friend Function
// Problem
class Human {
string secret;
public:
Human (string secret)
: secret(secret) {}
};
void tellSecret (Human h) {
cout << h.secret; // ERROR
}
int main() {
Human h("I have 2 gf:P\n");
tellSecret(h);
return 0;
}
Computer Programming II
Error. Non-member cannot
access private member.
Example: Friend Function
// Friend function solution
class Human {
string secret;
friend void tellSecret (Human);
public:
Human (string secret)
: secret(secret) {}
};
void tellSecret (Human h) {
cout << h.secret; // Fine
}
int main() {
Human h("I have 2 gf:P\n");
tellSecret(h);
return 0;
}
Output:
I have 2 gf:P
Computer Programming II
Grant tellSecret()
friendship.
tellSecret() is not a
member but friend
Fine. Friend function can
access private member.
Example: Friend Class
// Problem
class Human {
string secret;
public:
Human (string secret)
: secret(secret) {}
};
class Parrot {
public:
void tellSecret (Human h) {
cout << h.secret; // ERROR
}
};
Computer Programming II
int main() {
Human h("I have 2
gf:P\n");
Parrot b;
b.tellSecret(h);
return 0;
}
Error. Non-member
cannot access private
member.
Example: Friend Class
// Friend class solution
class Human {
friend class Parrot;
string secret;
public:
Human (string secret)
: secret(secret) {}
};
class Parrot {
public:
void tellSecret (Human h) {
cout << h.secret; // Fine
}
};
Computer Programming II
int main() {
Human h("I have 2 gf:P\n");
Parrot b;
b.tellSecret(h);
return 0;
}
Output:
I have 2 gf:P
Fine. Friend class can
access private member.
Exception Handling
Computer Programming II
Exception
When a program is executed, unexpected situation may
occur. Such a situation is called an exception
In other word: Exception is a runtime error caused by
some abnormal conditions
Example:
division by zero
failure of new operator to obtain a requested amount of
memory
Exception handler is code that handles the exception
(runtime error) when it occurs
Computer Programming II
10
Exception Example: Division By Zero
How to deal with the error below?
double divide (double x, double y) {
return x / y;
// divide by 0 if y = 0
}
int main() {
double x, y;
cin >> x >> y;
cout << "Result = " << divide (x, y);
return 0;
}
Computer Programming II
11
Exception Example: Division By Zero
A solution is shown below. It works but the codes that
handles the error mixes with the codes for division, making
the codes harder to read (if for division, else for error
handling, or the other way? No direct indication from
if/else keywords alone.
double divide (double x, double y) {
return x / y;
// divide by 0 if y = 0
}
int main() {
double x, y;
cin >> x >> y;
if (y == 0) cout << "Cannot divide by zero\n";
else
cout << "Result = " << divide (x, y);
return 0
}
Computer Programming II
12
Exception Handling
C++ implements exception handling using try, throw
and catch block
try block:
-Write the code that might generate runtime error within
the try block.
Format:
try {
// Code that may generate
// exceptions
}
Computer Programming II
13
try, throw, and catch blocks
throw statement:
-Use keyword throw in try block to signal that abnormal
condition or error has occurred.
-If the throw statement is executed, the codes in the try
block that appear after the throw statement won't be
executed.
Format:
try {
...
throw <object>;
...
}
<object> is to be replaced with type of object to be thrown.
Computer Programming II
14
try, throw, and catch blocks
catch block:
-Write the code that catches the thrown exception in
catch block. This is the exception handler.
-Unhandled/Uncaught thrown exception will terminate the
program.
Format:
try {
...
throw <object>;
...
}
catch (<Type of Exception>) {
error handling code;
}
Computer Programming II
15
Example: try, throw, and catch blocks
double divide (double x, double y) {
if (y == 0)
throw y;
return x / y;
}
int main() {
double x, y;
cin >> x >> y;
try {
double result = divide (x, y);
cout << "Result = " << result;
}
catch (double a) {
cout << "Cannot divide by zero\n";
}
return 0;
}
Computer Programming II
If there is an exception,
throw it
Put code that may
generate error in
try block
If there is no exception,
resume execution
If there is an exception
of type double,
catch it
16
Example: try, throw, and catch blocks
double divide (double x, double y) {
if (y == 0)
throw y;
return x / y;
}
int main() {
double x, y;
cin >> x >> y;
try {
double result = divide (x, y);
cout << "Result = " << result;
}
catch (double a) {
cout << "Cannot divide by
zero\n";
}
return 0;
}
Computer Programming II
Output1:No exception
1 2
Result = 0.5
Output2:With exception
1 0
Cannot divide by zero
The type of the object
being thrown must
match the type of the
parameter in the
catch block
17
Example: try, throw, and catch blocks
double divide (double x, double y) {
if (y == 0)
throw y;
return x / y;
}
int main() {
double x, y;
cin >> x >> y;
try {
double result = divide (x, y);
cout << "Result = " << result;
}
catch (double a) {
cout << "Cannot divide by zero\n";
}
return 0;
}
Computer Programming II
Output1:No exception
1 2
Result = 0.5
Output2:With exception
1 0
Cannot divide by zero
When an exception is
thrown, the codes
that appear after the
throw statement
won't be executed
18
Example: try, throw, and catch blocks
Note that you may throw a statement even without a function
int main() {
double x, y;
cin >> x >> y;
try {
if (y == 0)
throw y;
double result = x / y;
cout << "Result = " << result;
}
catch (double a) {
cout << "Cannot divide by zero\n";
}
return 0;
}
Computer Programming II
Output1:No exception
1 2
Result = 0.5
Output2:With exception
1 0
Cannot divide by zero
19
Exception Propagation
If the function/method containing the throw statement
does not catch the exception, the exception will be
propagated up to the caller of the function until it
reaches a try block or the main function.
In the former case, the try/catch block of the caller
handles the exception if the exception type matches
one of the catch block. Otherwise the exception will be
propagated up again.
If the exception has reached the main function and is
not handled, the program will be terminated.
Computer Programming II
20
Example: Exception Propagation
double divide2 (double x, double y) {
if (y == 0) throw y;
return x / y;
}
double divide1 (double x, double y) {
return divide2 (x, y);
}
double divide (double x, double y) {
return divide1 (x, y);
}
int main() {
...
try {
double result = divide (x, y);
cout << "Result = " << result;
}
catch (double a) {
...
Computer Programming II
Output:With exception
1 0
Cannot divide by zero
The exception is
propagated in the
following order:
divide2(),
divide1(),
divide(),
main()
The main() catches
and handles the
exception
21
Multiple catch Blocks
Some times, we might have many different exceptions
for a small block of code
1. We should write as many catch blocks.
2. This also means that we should have as
many throw statements.
3. BUT(usually), only one try block.
But, which catch block will be instigated/invoked?
Depend on the type of parameter
Computer Programming II
22
Multiple catch Blocks
try {
// Code that could generate an exception
}
catch (<Exception type1>) {
// Code that resolves a type1 exception
}
catch (<Exception type2>) {
// Code that resolves a type2 exception
}
catch (<Exception typeN>) {
// Code that resolves a typeN exception
} // end-of try-catch block
Only one catch block will be executed for an exception.
The catch block that first matches the exception type
would be chosen
Computer Programming II
23
Multiple catch Blocks
void func (int n) {
try {
if (n == 1) throw 11; // int
if (n == 2) throw 'a'; // char
cout << "n is not 1, 2 or 3\n";
}
catch (int a) {
cout << "Catch an int argument\n";
}
catch (char a) {
cout << "Catch a char argument\n";
}
catch (int a) {
cout << "Catch an int again\n";
}
}
Computer Programming II
int main () {
func (1);
func (2);
func (4);
return 0;
}
Output:
Catch an int argument
Catch a char argument
n is not 1, 2 or 3
This catch block first
matches int exception
type
24
Exception Matching
To catch every possible exception type, use ellipsis ""
try {
}
catch (...) { // catches all exceptions
}
Limitations of catch (...)
You can't tell what type of exception occurred
No argument to reference
Should always be placed as the last catch
Computer Programming II
25
Exception Matching
void func (int n) {
try {
if (n == 1) throw 11; // int
if (n == 2) throw 'a'; // char
if (n == 3) throw 3.5; // double
cout << "n is not 1, 2 or 3\n";
}
catch (int a) {
cout << "Catch an int argument\n";
}
catch (char a) {
cout << "Catch a char argument\n";
}
catch (...) { // all types
cout << "Not int nor char\n";
}
}
Computer Programming II
int main () {
func (1);
func (2);
func (3);
func (4);
return 0;
}
Output:
Catch an int argument
Catch a char argument
Not int nor char
n is not 1, 2 or 3
26
Advantages of Exception Handling
Using try, throw, and catch blocks to handle
exception offer the following advantages:
1.Provide clarify on the sections of codes that
handle the error
2.You may throw an exception in a
function/method, and handle it somewhere else
Computer Programming II
27