Determining exception type after the exception is caught?

前端 未结 9 1239
梦毁少年i
梦毁少年i 2020-12-01 01:20

Is there a way to determine the exception type even know you caught the exception with a catch all?

Example:

try
{
   SomeBigFunction();
}
catch(...)         


        
9条回答
  •  -上瘾入骨i
    2020-12-01 02:03

    Short Answer: No.

    Long Answer:

    If you derive all your exceptions from a common base type (say std::exception) and catch this explicitly then you can use this to get type information from your exception.

    But you should be using the feature of catch to catch as specific type of exception and then working from there.

    The only real use for catch(...) is:

    • Catch: and throw away exception (stop exception escaping destructor).
    • Catch: Log an unknwon exception happend and re-throw.

    Edited: You can extract type information via dynamic_cast<>() or via typid() Though as stated above this is not somthing I recomend. Use the case statements.

    #include 
    #include 
    
    class X: public std::runtime_error  // I use runtime_error a lot
    {                                   // its derived from std::exception
        public:                         // And has an implementation of what()
            X(std::string const& msg):
                runtime_error(msg)
            {}
    };
    
    int main()
    {
        try
        {
            throw X("Test");
        }
        catch(std::exception const& e)
        {
            std::cout << "Message: " << e.what() << "\n";
    
            /*
             * Note this is platform/compiler specific
             * Your milage may very
             */
            std::cout << "Type:    " << typeid(e).name() << "\n";
        }
    }
    

提交回复
热议问题