Exception Handling
- What will not be called when the terminate() is raised in the constructor?
-
View Hint View Answer Discuss in Forum
NA
Correct Option: A
destructor
- What is the output of this program?
#include <iostream>
using namespace std;
class BaseClass
{
protected:
int num;
public:
BaseClass()
{
num = 25;
}
BaseClass(int k)
{
num = k;
}
virtual ~BaseClass()
{
if (num < 0) throw num;
}
virtual int getA()
{
if (num < 0)
{
throw num;
}
}
};
int main()
{
try
{
BaseClass obj(-23);
cout << endl << obj.getA();
}
catch (int)
{
cout << endl << "Illegal initialization";
}
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: B
Compilation Error
main.cpp: In destructor ‘virtual BaseClass::~BaseClass()’:
main.cpp:18:33: warning: throw will always call terminate() [-Wterminate]
if (num < 0) throw num;
^~~
main.cpp:18:33: note: in C++11 destructors default to noexcept
main.cpp: At global scope:
main.cpp:39:5: fatal error: error writing to /tmp/cci28TfS.s: No space left on device
}
^
compilation terminated.
- What is the output of this program?
#include <iostream>
#include <exception>
using namespace std;
void terminatorFunction()
{
cout << "terminate" << endl;
}
void (*old_terminate)() = set_terminate(terminatorFunction);
class BotchClass
{
public:
class Fruits {};
void f()
{
cout << "First" << endl;
throw Fruits();
}
~BotchClass() noexcept(false)
{
throw 'U';
}
};
int main()
{
try
{
BotchClass obj;
obj.f();
}
catch(...)
{
cout << "inside catch(...) block" << endl;
}
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: A
This program uses set_terminate as it is having an uncaught exception.
- What is the output of this program?
#include <iostream>
#include <exception>
#include <cstdlib>
using namespace std;
void TerminateFunction()
{
cout << "terminate handler called...";
abort();
}
int main (void)
{
set_terminate (TerminateFunction);
throw 0;
return 0;
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: D
In this program, We are using set_terminate to abort the program.
- What is the output of this program?
#include <iostream>
using namespace std;
class TestClassA
{
};
class TestClassB : public TestClassA { };
void Function();
int main()
{
try
{
Function();
}
catch (const TestClassA&)
{
cout << "Caught an exception" << endl;
}
return 0;
}
void Function()
{
throw TestClassB();
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: A
In this program, We are arising with the exception by using the method in the class.