如何抛出 C++ 异常

How to throw a C++ exception(如何抛出 C++ 异常)
本文介绍了如何抛出 C++ 异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我对异常处理的理解很差(即,如何为自己的目的自定义 throw、try、catch 语句).

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

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

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

我希望函数在 a 或 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?

推荐答案

简单:

#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... 
}

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

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;
}

并捕获不分类型的异常:

And to catch exceptions regardless of type:

catch( ... ) { };

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do compilers treat variable length arrays(编译器如何处理变长数组)
Deduce template argument from std::function call signature(从 std::function 调用签名推导出模板参数)
check if member exists using enable_if(使用 enable_if 检查成员是否存在)
Standard Library Containers with additional optional template parameters?(具有附加可选模板参数的标准库容器?)
Uses of a C++ Arithmetic Promotion Header(C++ 算术提升标头的使用)
Parameter pack must be at the end of the parameter list... When and why?(参数包必须位于参数列表的末尾...何时以及为什么?)