Exception Handling
- What is the output of this program?
#include <iostream>
using namespace std;
int main()
{
int num = -2;
try
{
if (num < 0)
{
throw num;
}
else
{
cout<< num;
}
}
catch (int num )
{
cout << "Exception occurred: Thrown value is " << num << endl;
}
return 0;
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: D
As the given value is -2 and according to the condition, We are arising an exception.
- What is the output of this program?
#include <iostream>
#include <typeinfo>
using namespace std;
class Poly
{
virtual void Member(){}
};
int main ()
{
try
{
Poly * ptr = 0;
typeid(*ptr);
}
catch (exception& ex)
{
cout << "An Exception caught: " << ex.what() << endl;
}
return 0;
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: C
In this program, We used a bad type id for the polymorphic operator, So it is arising an bad_typeid exception.
- What is the output of this program?
#include <iostream>
#include <exception>
using namespace std;
void Function()
{
cout << "Unexpected handler called\n";
throw;
}
void NewFunction () throw (int,bad_exception)
{
throw 'U';
}
int main (void)
{
set_unexpected (Function);
try
{
NewFunction();
}
catch (int)
{
cout << "caught int\n";
}
catch (bad_exception be)
{
cout << "Caught Bad_exception\n";
}
catch (...)
{
cout << "Caught other exception \n";
}
return 0;
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: B
In this program, We are calling set_unexpected and NewFunction, So it is printing the output.
- What is the output of this program?
#include <iostream>
using namespace std;
int main()
{
int num = -2;
char *p;
p = new char[50];
try
{
if (num < 0)
{
throw num;
}
if (p == NULL)
{
throw "p is NULL ";
}
}
catch (...)
{
cout << "Exception occurred: exiting"<< endl;
}
return 0;
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: D
catch(…) is used to catch all types of exceptions arising in the program.
- What is the output of this program?
#include <iostream>
#include <exception>
using namespace std;
void Function ()
{
cout << "Unexpected called\n";
throw 0;
}
void myfunction () throw (int)
{
throw 'L';
}
int main ()
{
set_unexpected (Function);
try
{
myfunction();
}
catch (int)
{
cout << "Caught int\n";
}
catch (...)
{
cout << "caught other exception\n";
}
return 0;
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: B
As we are calling set_unexpected (myunexpected) function, this is printing as unexpected called and because of operator compliance it is arising an exception.