Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ catch enum value as exception

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?

like image 806
Chau Avatar asked Jan 06 '14 13:01

Chau


2 Answers

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");
}
like image 54
utnapistim Avatar answered Oct 02 '22 18:10

utnapistim


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");
}
like image 23
Olaf Dietsche Avatar answered Oct 02 '22 18:10

Olaf Dietsche