Q:

Catch an pre-defined int exception

I have defined a simple int error code:
#define my_error 20

Somewhere in my code I throw this error:
throw my_error;

Now I want to try and catch this exception thrown:
try
{
    ...
    ...
}
catch (my_error)
{
    cout << "Error: my error";
}

Unfortunately the compiler doesn't approve this:

syntax error : 'constant'
catch handlers must specify one type
'try' block starting on line '34' has no catch handlers

Is there a way to do this?

A:

20 is not a type, so you can't catch it. What you can do is filter the values in the catch block:
catch (int exception)
{
    if ( exception == 20 )
        cout << "Error: my error";
}

An even better approach would be to define your own exception:
class MyException : public std::exception
{
}

//...

try
{
   throw MyException();
}
catch(MyException& ex)
{
}

A:

If you use C++11, you can use decltype(my_error), just in case you ever change the type of my_error.
try {
  // ...
} catch (const decltype(my_error)& e) {
  // ...
}

Here is a demo.

