如何引发C ++异常

我对异常处理的理解很差(即,如何出于我的目的自定义throw,try,catch语句)。

例如,我定义了一个函数,如下所示: int compare(int a, int b){...}

我希望函数在a或b为负数时引发一些消息异常。

在函数的定义中应该如何处理?

桑德斯

简单:

#include <stdexcept>

int compare( int a, int b ) {
    if ( a < 0 || b < 0 ) {
        throw std::invalid_argument( "received negative value" );
    }
}

标准库带有不错的内置异常对象集合,您可以抛出这些异常对象请记住,您应该始终按值抛出并按引用进行捕获:

try {
    compare( -1, 3 );
}
catch( const std::invalid_argument& e ) {
    // do stuff with exception... 
}

每次尝试后可以有多个catch()语句,因此可以根据需要分别处理不同的异常类型。

您还可以重新引发异常:

catch( const std::invalid_argument& e ) {
    // do something

    // let someone higher up the call stack handle it if they want
    throw;
}

并捕获异常,无论类型如何:

catch( ... ) { };

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章