Determining exception type after the exception is caught?

前端 未结 9 1127
梦毁少年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条回答
  • 2020-12-01 02:05

    No.

    Doing so would at the very least require you to be able to access the current exception. I do not believe there is a standard way of doing this.

    Once you had the exception instance, you would have to use a type inspection algorithm. C++ doesn't have inherent support for this. At best you would have to have a big if/elseif statement with dynamic_cast's to check the type.

    0 讨论(0)
  • 2020-12-01 02:06

    provided that c++11 available,

    bool throwing_func()
    {
        // something is wrong...
        throw char('5');
    
        // ...
    
        return true;
    }
    
    void exception_handler(std::exception_ptr _Eptr)
    {
        try 
        {
            if (_Eptr) {std::rethrow_exception(_Eptr);}
        }
    
    
        catch(int _Xi)
        {
            std::cout << "int\n";
        }
    
        catch(char _Xc)
        {
            std::cout << "char\n";
        }
    
        catch(const std::exception& _Xe)
        {
           std::cout << "std::exception " << _Xe.what() << "\n";
        }
    
        catch (...)
        {// develop more catch cases above to avoid what follows
            std::cout << "unhandled exception\n";
            // grande problema
        }
    }
    
    int main()
    {
    
        try
        {
            throwing_func();
        }
    
        catch(...)
        {
            //Determine exception type here
    
             exception_handler(std::current_exception());
        }
    
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-01 02:09

    If you need to handle exceptions differently based on what they are, you should be catching specific exceptions. If there are groups of exceptions that all need to be handled identically, deriving them from a common base class and catching the base class would be the way to go. Leverage the power and paradigms of the language, don't fight against them!

    0 讨论(0)
提交回复
热议问题