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;
}

Recommended Answers

All 4 Replies

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

use a typecast in the throw tag

throw (char *)"Value is zero";

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

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.