Catch predefined int exception

I 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:

try
{
    ...
    ...
}
catch (my_error)
{
    cout << "Error: my error";
}

Unfortunately, the compiler does not approve of this:

  • Syntax error: constant
  • catch handlers must specify one type
  • 'try' block starting at line '34' has no catch handlers

Is there any way to do this?

Thanks.

+1
source share
2 answers

20is not a type, so you cannot catch it. What you can do is filter the values ​​in a block catch:

catch (int exception)
{
    if ( exception == 20 )
        cout << "Error: my error";
}

An even better approach is to define your own exception:

class MyException : public std::exception
{
}

//...

try
{
   throw MyException();
}
catch(MyException& ex)
{
}
+7
source

++ 11, decltype(my_error), - my_error.

try {
  // ...
} catch (const decltype(my_error)& e) {
  // ...
}

.

+1

All Articles