如何抛出C ++异常 [英] How to throw a C++ exception

查看:497
本文介绍了如何抛出C ++异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对异常处理有很差的理解(例如,如何为我自己的目的定制throw,try,catch语句)。



定义一个函数如下: int compare(int a,int b){...}



< d当函数a或b为负时,函数会抛出一个异常。



我应该如何在函数定义中处理这个问题?

解决方案

简单:

  #include< stdexcept> 

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

标准库提供了一个漂亮的内置异常对象。请记住,您应该始终按值引用并按引用捕获:

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

每次尝试后可以有多个catch()语句,因此如果需要,您可以单独处理不同的异常类型。



您还可以重新抛出异常:

  catch std :: invalid_argument& e){
//做某事

//让某人更高的调用堆栈处理它,如果他们想要
throw e;
}

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

  catch(...){}; 


I have a very poor understanding of exception handling(i.e., how to customize throw, try, catch statements for my own purposes).

For example, I have defined a function as follows: int compare(int a, int b){...}

I'd like the function to throw an exception with some message when either a or b is negative.

How should I approach this in the definition of the function?

解决方案

Simple:

#include <stdexcept>

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

The Standard Library comes with a nice collection of built-in exception objects you can throw. Keep in mind that you should always throw by value and catch by reference:

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

You can have multiple catch() statements after each try, so you can handle different exception types separately if you want.

You can also re-throw exceptions:

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

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

And to catch exceptions regardless of type:

catch( ... ) { };

这篇关于如何抛出C ++异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆