【问题标题】:Catch multiple exceptions捕获多个异常
【发布时间】:2020-05-10 02:28:14
【问题描述】:

我怎样才能同时catch 多个异常?

我的意思是,如果我得到std::out_of_rangestd::invalid_argument,我必须做A,如果我得到std::runtime_errorstd::bad_alloc,我必须做B

这是一个例子……在某些情况下,我有超过 5 个例外情况让我明白了这一点。

我只是希望我不必多次复制粘贴相同的代码!

【问题讨论】:

    标签: c++ exception try-catch


    【解决方案1】:

    你不复制'n'粘贴,你将代码放在函数中并在多种情况下调用函数。

    方法如下:

    try {
        /* Stuff */
    } catch (const std::out_of_range&) {
        do_A();
    } catch (const std::invalid_argument&) {
        do_A();
    } catch (const std::runtime_error&) {
        do_B();
    } catch (const std::bad_alloc&) {
        do_B();
    }
    

    如果您需要在多个位置进行相同的异常处理,您可以将其放入一个函数中,如下所示:

    void handle_exception() {
        try {
            throw; // re-throw the original exception our caller caught, so we can catch and handle specific ones.
        } catch (const std::out_of_range&) {
            do_A();
        } catch (const std::invalid_argument&) {
            do_A();
        } catch (const std::runtime_error&) {
            do_B();
        } catch (const std::bad_alloc&) {
            do_B();
        }
    }
    

    然后,在多个地方,您可以这样做

    try {
        /* Stuff */
    } catch (...) {
        handle_exception();
    }
    

    【讨论】:

    • 谢谢...我希望有一个不同的解决方案(比如一次捕获更多异常),但我认为这是最好的解决方案!
    • @Foxel 扩展了我的答案,以帮助您在多个位置需要相同的异常处理时减少重复代码。
    猜你喜欢
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 2010-09-13
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    相关资源
    最近更新 更多