0

The output of the code below is:

start
Caught One! Ex. #: 1
Caught One! Ex. #: 2
Abnormal Program Termination

I don't understand why the exception isn't caught.

#include <iostream>
using namespace std;
// Different types of exceptions can be caught.
void Xhandler(int test)
{
try{
if(test) throw test;
else throw "Value is zero";
}
catch(int i) {
cout << "Caught One! Ex. #: " << i << '\n';
}
catch(char *str) {
cout << "Caught a string: ";
cout << str << '\n';
}
}
int main()
{
cout << "start\n";
Xhandler(1);
Xhandler(2);
Xhandler(0);
Xhandler(3);
cout << "end";
return 0;
}
4
Contributors
4
Replies
5
Views
8 Years
Discussion Span
Last Post by HappyOrangutan
0

I'm not sure what your problem is, when I compile and run it:

start
Caught One! Ex. #: 1
Caught One! Ex. #: 2
Caught a string: Value is zero
Caught One! Ex. #: 3
end

0

use a typecast in the throw tag

throw (char *)"Value is zero";

it should work. I have tried in my machine by using it.

0

If at all you want to throw string literals, remember that they are const char* not simply char*. So refactor your code as:

void Xhandler(int test)
{
    try
    {
        if (test) throw test;
        else throw "Value is zero";
    }
    catch (int i)
    {
        cout << "Caught One! Ex. #: " << i << '\n';
    }
    catch (const char *str)
    {
        cout << "Caught a string: ";
        cout << str << '\n';
    }
}

But then, before you find throwing string literals very comfortable, read this article http://www.informit.com/articles/article.aspx?p=30642&seqNum=5

0

Thank you siddhant3s, that solved the problem. I will give the article a good read.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.