C++ catch enum value as exception

邮差的信 提交于 2019-12-10 17:56:42

问题


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?


回答1:


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");
}



回答2:


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");
}


来源:https://stackoverflow.com/questions/20951134/c-catch-enum-value-as-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!