C++ throw抛出异常用法详解
异常处理是许多现代编程语言中不可或缺的一部分,C++ 也不例外。通过使用 throw、try、和 catch 关键字,C++ 为程序员提供了强大的异常处理机制。
在这篇文章中,我们专门讲解 throw 关键字的用法,并通过实例代码来详细解释。
例如:
下面是一个完整的例子:
如下是从 <stdexcept> 头文件中摘录的一部分异常类:
在这篇文章中,我们专门讲解 throw 关键字的用法,并通过实例代码来详细解释。
throw的基础用法
throw 是 C++ 异常处理机制中的一个关键字,用于在检测到异常情况时触发异常,语法格式如下:throw 异常信息;异常信息可以是一个变量,也可以是一个表达式,表示要抛出的异常对象。
例如:
throw 1; // 抛出一个整数的异常 throw “abced”; // 抛出一个字符串的异常 throw int; // 错误,异常信息不能是类型,必须是具体的值当在代码中检测到一个异常情况(如非法输入、资源耗尽等)时,可以使用 throw 关键字来抛出一个异常。这通常会中断当前函数的执行,并将控制权转交给最近的 catch 块。
下面是一个完整的例子:
#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;
}
运行结果为:
Caught a string exception: String type exception
C++异常类
throw 抛出的异常值,可以是基本数据类型,也可以是类类型。C++ 标准库中提供了一些常见的异常类,它们定义在<stdexcept>头文件中。如下是从 <stdexcept> 头文件中摘录的一部分异常类:
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; // 当算术运算导致下溢时抛出。
}
举个简单的例子:
#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;
}
运行结果为:
Result: 5
Caught exception: Denominator cannot be zero
ICP备案:
公安联网备案: