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++ 异常


基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01