Program Design Including Data Structures Ch 14 Questions 1. What is the differen
ID: 3851711 • Letter: P
Question
Program Design Including Data Structures Ch 14 Questions
1. What is the difference between a try block and a catch block?
2. Consider the following C++ code:
double balance;
try
{
cout << "Enter the balance: ";
cin >> balance;
cout << endl;
if (balance < 1000.00)
throw balance;
cout << "Leaving the try block." << endl;
}
catch (double x)
{
cout << "Current balance: " << x << endl
<< "Balance must be greater than 1000.00" << endl;
}
a. In this code, identify the try block.
b. In this code, identify the catch block.
c. In this code, identify the catch block parameter and its type.
d. In this code, identify the throw statement.
4. If you define your own exception class, what is typically included in that class?
5. Suppose the exception class myException is defined as follows:
class myException
{
public:
myException()
{
message = "myException thrown!";
cout << "Immediate attention required!" << endl;
}
myException(string msg)
{
message = msg;
cout << "Attention required!" << endl;
}
string what()
{
return message;
}
private:
string message;
}
Suppose that in a user program, the catch block has the following form:
catch (myException mE)
{
cout << mE.what() << endl;
}
a. What output will be produced if the exception is thrown with the default constructor?
b. Also, what output will be produced if the exception is thrown with the constructor with parameters with the following actual parameter? "May Day, May Day"
5. Name three exception-handling techniques.
Explanation / Answer
1.
try block is used to enclose the code that can throw an exception and catch block is used to handle the exception thrown by try block. We can have multiple catch blocks to handle different types of exceptions associated with one try block.
2.
a. try block.
try
{
cout << "Enter the balance: ";
cin >> balance;
cout << endl;
if (balance < 1000.00)
throw balance;
cout << "Leaving the try block." << endl;
}
b. catch block.
catch (double x)
{
cout << "Current balance: " << x << endl
<< "Balance must be greater than 1000.00" << endl;
}
c. catch block parameter and its type.
double x
d. throw statement.
f (balance < 1000.00)
throw balance;
4. Inside the exception class, the default and/or argument constructor is defined and the methods returning the error messages are defined.
5.
a. with default constructor
So ,message = "myException thrown!";
mE.what() outputs:
myException thrown!
b. argument constructor
So ,message = "myException thrown!";
Output:
"Immediate attention required!"
myException thrown!
5.
Attention required!
May Day, May Day
5. Exception handling techniques:
a. try catch blocks
b. using inbuilt Exception classes
c. using user defined exception classes
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.