How to throw a C++ exception(如何抛出 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++ 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何抛出 C++ 异常
基础教程推荐
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- c++ STL设置差异 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
