How to throw good exceptions?

前端 未结 12 1390
情话喂你
情话喂你 2020-12-14 21:05

I heard you should never throw a string because there is a lack of information and you\'ll catch exceptions you dont expect to catch. What are good practice for throwing exc

12条回答
  •  鱼传尺愫
    2020-12-14 21:59

    Here is a simple example of throwing an exception that takes barely any resources:

    class DivisionError {};
    class Division
    {
    public:
        float Divide(float x, float y) throw(DivisionError)
        {
            float result = 0;
            if(y != 0)
                result = x/y;
            else
                throw DivisionError();
            return result;
        }
    };
    
    int main()
    {
        Division d;
        try
        {
            d.Divide(10,0);
        }
        catch(DivisionError)
        {
            /*...error handling...*/
        }
    }
    

    The empty class that is thrown does not take any resource or very few...

提交回复
热议问题