1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
using namespace std;
string a(const string &s)
{
if (s == "A") throw (string) "B";
try {
if (s == "C") throw (string) "D";
return "E";
} catch (const string &t) {
cout << t;
}
return "F";
}
int main()
{
string t;
cin >> t;
try {
cout << a(t);
} catch (const string &s) {
cout << s;
}
cout << endl;
return 0;
}
Please read over the code to the right, and assume that this is compiled to a.out.
Question 1: What is the output of:
UNIX> echo A | ./a.out
UNIX> echo A | ./a.out BWhen "A" is entered and passed to the procedure a(), the procedure throws the string "B". That throw statement is not inside a try, so the exception is passed to the calling procedure main(). main() catches the exception and prints "B". It then prints a newline and exits.
Question 2: What is the output of:
UNIX> echo B | ./a.out
UNIX> echo B | ./a.out EWhen "B" is entered and passed to the procedure a(), both if statements are false, so no exceptions are thrown. a() returns "E" to the caller, which prints it out, and then prints a newline.
Question 3: What is the output of:
UNIX> echo C | ./a.out
UNIX> echo C | ./a.out DFWhen "C" is entered and passed to the procedure a(), the procedure throws the string "D". That is caught in a(), which prints "D". After the catch code, it returns "F". main() prints "R" and a newline.
Question 4: What is the output of:
UNIX> echo D | ./a.out
UNIX> echo D | ./a.out EAny string that is not "A" or "C" will be identical to question 2.