C++ get description of an exception caught in catch(…) block

前端 未结 6 1885
感动是毒
感动是毒 2020-12-03 10:07

can I get description of an exception caught by

catch(...)

block? something like .what() of std::exception.

6条回答
  •  暖寄归人
    2020-12-03 10:37

    If you know you only throw std::exception or subclasses, try

    catch(std::exception& e) {...e.what()... }
    

    Otherwise, as DeadMG wrote, since you can throw (almost) everything, you cannot assume anything about what you caught.

    Normally catch(...) should only be used as the last defense when using badly written or documented external libraries. So you would use an hierarchy

    catch(my::specialException& e) {
          // I know what happened and can handle it
          ... handle special case
          }
    catch(my::otherSpecialException& e) {
          // I know what happened and can handle it
          ... handle other special case
          }
    catch(std::exception& e) {
          //I can at least do something with it
          logger.out(e.what());
          }
    catch(...) {
         // something happened that should not have 
         logger.out("oops");
         }
    

提交回复
热议问题