This section contains the C++ find output programs with their explanations on C++ Exceptional Handling (set 3).
Program 1:
#include <iostream>
#include <exception>
using namespace std;
union UserException : public exception {
const char* message() const throw()
{
return "My User Exception";
}
};
int main()
{
try {
throw UserException();
}
catch (UserException E) {
cout << E.message();
}
return 0;
}
Program 2:
#include <iostream>
#include <exception>
using namespace std;
void expFun(char* ptr)
{
if (ptr == NULL)
throw "NULL Exception";
}
int main()
{
expFun(NULL);
catch (const char* E)
{
cout << E;
}
return 0;
}
Program 3:
#include <iostream>
#include <exception>
using namespace std;
void expFun(char* ptr)
{
try {
if (ptr == NULL)
throw "NULL Exception";
}
}
int main()
{
expFun(NULL);
catch (const char* E)
{
cout << E;
}
return 0;
}
Program 4:
#include <iostream>
#include <exception>
using namespace std;
void expFun(char* ptr)
{
if (ptr == NULL)
throw "NULL Exception";
}
int main()
{
try {
expFun(NULL);
}
catch (const char* E) {
cout << E;
}
return 0;
}
Program 5:
#include <iostream>
using namespace std;
int main()
{
try {
try {
throw 101;
}
catch (int num) {
cout << "Here we re-throw the exception" << endl;
throw;
}
}
catch (int num) {
cout << "Exception code: " << num << endl;
}
return 0;
}
Answer Program1:
Output:
Explanation:
It will generate a compilation error because we cannot inherit any class into the "union". Here we inherited exception class into "UserException" union.
Answer Program 2:
Output:
Explanation:
It will generate the compile-time error, because we did not create any "try" block but we used catch block in the above program, so we need to define a "try" block to resolve the problem.
Answer Program 3:
Output:
Explanation:
It will generate the compile-time error because in the main() function, we did not create any "try" block but we used catch block in the above program, so we need to define a "try" block in the same function with a catch block.
Note: The “try” and “catch” must be present in the same function.
Answer Program 4:
Output:
Explanation:
Here, we defined a function expFun() with the character pointer as an argument, and we check if the value of pointer ptr is NULL then it will throw a constant string that will be caught by the corresponding catch block.
In the main() function. Here we called expFun() function in the try block and pass NULL as an argument, that’s why function expFun() thrown an exception which is caught by catch block and print the message on the console screen.
Answer Program 5:
Output:
Explanation:
Here, we created a nested try and catch block, here we thrown an integer number 101, then caught and print the message after that re-throw the exception using "throw" keyword, and finally caught the exception and print received exception code by the outer catch block.
need an explanation for this answer? contact us directly to get an explanation for this answer