Reputation: 1017
Try/catch block in C++ not being "caught." I'm trying to have one catch block to get all exceptions.
#include <iostream>
#include <exception>
using namespace std;
int main()
{
try
{
throw 1;
}
catch (exception& e)
{
cout << "ERROR: " << e.what() << endl;
return 1;
}
return 0;
}
Upvotes: 0
Views: 267
Reputation: 519
You are throwing an int
, but only catching std::exception
. Use a catch(...)
to catch everything thrown.
Upvotes: 0
Reputation: 66922
throw 1;
will throw an int
. As you do not catch an int
, the exception goes uncaught, which is undefined behavior. Though it is possible to throw anything, always prefer to throw a class that derives from std::exception
. You can catch an int
with catch(int e)
or catch(...)
, but there's really no reason to ever do that.
If you catch with catch(...)
, then you do not know the type of the object, so cannot access any members, properties, or other aspects, and so you cannot* gather any information about what was thrown. This should never be used.
*There are ways to get information about the thrown object, but it's far easier to just catch the right type in the first place
Upvotes: 6