Here is a listing of C++ programming questions on “Uncaught Exceptions” along with answers, explanations and/or solutions:
1. What happens if try catch block is not used?
a) arise an error
b) program will run
c) execute continuously
d) wrong output
Answer: a
Clarification: If try catch block is not used the exception thrown by the program will be uncaught hence will result into error(s).
2. Which handler is used to handle all types of exception?
a) catch handler
b) catch-all handler
c) catch-none handler
d) try-catch handler
Answer: b
Clarification: To catch all types of exceptions, we use the catch-all handler.
3. Which operator is used as catch-all handler?
a) ellipses operator
b) ternary operator
c) string operator
d) unary operator
Answer: a
Clarification: The ellipses operator can be represented as (…).
4. What will be the output of the following C++ code?
-
#include -
using namespace std;
-
class Base -
{ -
protected:
-
int a;
-
public:
-
Base()
-
{ -
a = 34;
-
} -
Base(int i)
-
{ -
a = i;
-
} -
virtual ~Base()
-
{ -
if (a < 0) throw a;
-
} -
virtual int getA()
-
{ -
if (a < 0)
-
{ -
throw a;
-
} -
} -
};
-
int main()
-
{ -
try -
{ -
Base b(-25);
-
cout << endl << b.getA();
-
} -
catch (int)
-
{ -
cout << endl << "Illegal initialization";
-
} -
}
a) Illegal initialization
b) Terminate called after throwing an instance of ‘int’
c) Illegal initialization & terminate called after throwing an instance
d) initialization
Answer: b
Clarification: As we are throwing a negative number and we are using the only integer, So it is arising an error.
Output:
$ g++ uce.cpp $ a.out terminate called after throwing an instance of 'int'
5. What will be the output of the following C++ code?
-
#include -
#include -
using namespace std;
-
void terminator()
-
{ -
cout << "terminate" << endl;
-
} -
void (*old_terminate)() = set_terminate(terminator);
-
class Botch -
{ -
public:
-
class Fruit {};
-
void f()
-
{ -
cout << "one" << endl;
-
throw Fruit();
-
} -
~Botch()
-
{ -
throw 'c';
-
} -
};
-
int main()
-
{ -
try -
{ -
Botch b; -
b.f();
-
} -
catch(...)
-
{ -
cout << "inside catch(...)" << endl;
-
} -
}
a) one
b) inside catch
c)
one terminate
d)
one terminate Aborted
View Answer
Clarification: This program uses set_terminate as it is having an uncaught exception.
Output:
$ g++ uce1.cpp $ a.out one terminate Aborted
6. What will be the output of the following C++ code?
-
#include -
#include -
#include -
using namespace std;
-
void myterminate ()
-
{ -
cerr << "terminate handler called";
-
abort();
-
} -
int main (void)
-
{ -
set_terminate (myterminate);
-
throw 0;
-
return 0;
-
}
a) terminate handler called
b) aborted
c) both terminate handler & Aborted
d) runtime error
Answer: c
Clarification: In this program, We are using set_terminate to abort the program.
Output:
$ g++ uce2.cpp $ a.out terminate handler called Aborted
