C/C++ 异常处理机制详解
- 作者: 刘杰
- 来源: 技术那些事
- 阅读:207
- 发布: 2025-07-03 07:09
- 最后更新: 2025-07-04 10:26
C++ throw抛出异常用法详解
异常处理是许多现代编程语言中不可或缺的一部分,C++ 也不例外。通过使用 throw、try、和 catch 关键字,C++ 为程序员提供了强大的异常处理机制。
throw的基础用法
throw 是 C++ 异常处理机制中的一个关键字,用于在检测到异常情况时触发异常,语法格式:throw [异常信息]。异常信息可以是一个变量,也可以是一个表达式,表示要抛出的异常对象。
示例:
c++
throw 1; // 抛出一个整数的异常
throw “abced”; // 抛出一个字符串的异常
throw int; // 错误,异常信息不能是类型,必须是具体的值
当在代码中检测到一个异常情况(如非法输入、资源耗尽等)时,可以使用 throw 关键字来抛出一个异常。这通常会中断当前函数的执行,并将控制权转交给最近的 catch 块。
示例:
c++
#include <iostream>
void testFunction(int choice) {
if (choice == 1) {
throw 42;
}
else if (choice == 2) {
throw "String type exception";
}
else {
throw 1.23;
}
}
int main() {
try {
testFunction(2);
}
catch (int e) {
std::cout << "Caught an integer exception: " << e << std::endl;
}
catch (const char* e) {
std::cout << "Caught a string exception: " << e << std::endl;
}
catch (const double& e) {
std::cout << "Caught a standard exception: " << e << std::endl;
}
return 0;
}
C++异常类
throw 抛出的异常值,可以是基本数据类型,也可以是类类型。C++ 标准库中提供了一些常见的异常类,它们定义在<stdexcept>头文件中。
如下是从
c++
namespace std
{
class logic_error; // logic_error: 表示程序逻辑错误的基类。
class domain_error; // 当数学函数的输入参数不在函数的定义域内时抛出。
class invalid_argument; // 当函数的一个参数无效时抛出。
class length_error; //当操作导致容器超过其最大允许大小时抛出。
class out_of_range; // 当数组或其他数据结构访问越界时抛出。
class runtime_error;// 表示运行时错误的基类。
class range_error; // 当数学计算的结果不可表示时抛出。
class overflow_error; // 当算术运算导致溢出时抛出。
class underflow_error; // 当算术运算导致下溢时抛出。
}
示例
c++
#include <iostream>
#include <stdexcept>
void divideNumbers(double num1, double num2) {
if (num2 == 0) {
throw std::invalid_argument("Denominator cannot be zero");
}
std::cout << "Result: " << num1 / num2 << std::endl;
}
int main() {
try {
divideNumbers(10, 2);
divideNumbers(10, 0);
} catch (const std::invalid_argument& e) {
std::cerr << "Caught exception: " << e.what() << std::endl;
}
return 0;
}
在上述代码中,divideNumbers() 函数接受两个浮点数,并尝试进行除法。如果除数(denominator)是 0,则通过 throw 关键字抛出一个 std::invalid_argument 异常。这个异常会被 main() 函数中的 catch 块捕获,并输出相应的错误消息。
exception 类
