如何抛出 C++ 异常

2023-03-07C/C++开发问题
1

本文介绍了如何抛出 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++ 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6