Exception Handling
- What is the output of this program?
#include <iostream>
#include <string>
using namespace std;
int main ()
{
int n = 5;
string str = "Exception Caught: Wrong number used";
try
{
if ( n == 1 )
{
throw 10;
}
if ( n == 2 )
{
throw 3.5f;
}
if ( n != 1 || n != 2 )
{
throw str;
}
}
catch (int p)
{
cout << "Exception value is: " << p << endl;
}
catch (float q)
{
cout << "Exception value is: " << q << endl;
}
catch (string str)
{
cout << str << endl;
}
return 0;
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: D
As we are giving 5 to n, It is arising an exception named
“Exception Caught: Wrong number used”.
- What is the output of this program?
#include <iostream>
using namespace std;
double Div(int num1, int num2)
{
if (num2 == 0)
{
throw "Division by zero condition!";
}
return (num1 / num2);
}
int main ()
{
int p = 25;
int q = 0;
double Res = 0;
try
{
Res = Div(p, q);
cout << Res << endl;
}
catch (const Message)
{
cerr << Message << endl;
}
return 0;
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: A
As we missed the data type in the catch block, It will arise an error.
- Which alternative can replace the throw statement?
-
View Hint View Answer Discuss in Forum
NA
Correct Option: D
throw and return does the same job as return a value. So it can be replaced.
- What are the disadvantages if use return keyword to return error codes?
-
View Hint View Answer Discuss in Forum
NA
Correct Option: D
As we are using return for each and every exception, It will definitely increase the code size.
- What is most suitable for returning the logical errors in the program?
-
View Hint View Answer Discuss in Forum
NA
Correct Option: A
Set a global error indicator