7

I am trying to use an external C++ library which have defined its exceptions as:

enum MY_ERRORS { ERR_NONE = 0, ERR_T1, ERR_T2, }; 

Then in the code exceptions are thrown like this:

if(...) { throw ERR_T1; 

Being new to programming in C++, I would do something like:

try { call_to_external_library(); } catch(??? err) { printf("An error occurred: %s\n", err); } catch(...) { printf("An unexpected exception occurred.\n"); } 

How do I determine what was thrown?

2
  • 1
    possible duplicate of Catch an pre-defined int exception Commented Jan 6, 2014 at 13:36
  • 2
    err should be MY_ERRORS or const MY_ERRORS& or something like this (doesn't matter much for enums). In the catch( ... ) you cannot get the type of the caught exception Commented Jan 6, 2014 at 13:36

2 Answers 2

8

You will need to write your code to handle the type of enumeration in the catch block:

try { call_to_external_library(); } catch(MY_ERRORS err) { // <------------------------ HERE printf("An error occurred: %s\n", err); } catch(...) { printf("An unexpected exception occurred.\n"); } 
Sign up to request clarification or add additional context in comments.

1 Comment

You might consider wrapping the enum in a type that derives from std::exception so that it can be caught like a normal exception. Not necessary, but it can be nice to have a more uniform way to catch things.
5

You must catch the type MY_ERRORS and then compare against the possible values

try { call_to_external_library(); } catch(MY_ERRORS err) { printf("An error occurred: %s\n", err); } catch(...) { printf("An unexpected exception occurred.\n"); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.