C++学习, 异常处理
C++ 提供了异常处理机制,允许程序在运行时检测和处理错误情况。这种机制通过 try
、catch
和 throw
关键字来实现。当程序遇到异常情况时,它可以抛出一个异常,然后控制权转移到能够处理该异常的代码块。
基本概念
- throw:用于抛出一个异常。它可以抛出 C++ 中的任何类型的数据,但通常是派生自
std::exception
的对象。 - try:用于标记一个代码块,该代码块内的异常将被捕获并处理。
- catch:用于捕获并处理异常。可以指定捕获特定类型的异常,或者捕获所有类型的异常(使用省略号
...
)。
try/catch 语句用法:
try
{
// 保护代码
}catch( ExceptionName e1 )
{
// catch 块
}catch( ExceptionName e2 )
{
// catch 块
}catch( ExceptionName eN )
{
// catch 块
}
throw 语句用法:
double division(int a, int b)
{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
异常处理示例:
#include <iostream>
#include <stdexcept> // 包含 std::runtime_error
void mightGoWrong() {
// 假设这里有一段可能出错的代码
throw std::runtime_error("Something went wrong!");
}
int main() {
try {
mightGoWrong(); // 这里可能会抛出异常
std::cout << "This line won't be executed if an exception is thrown.\n";
} catch (const std::runtime_error& e) {
// 捕获 std::runtime_error 类型的异常
std::cerr << "Caught an exception: " << e.what() << '\n';
}
// 这里的代码会继续执行,即使 mightGoWrong() 中抛出了异常
std::cout << "Execution continues after the exception.\n";
return 0;
}