C++异常处理提供了一种在程序运行期间处理运行时错误的方法。通过使用异常处理,您可以更清晰地分隔正常代码和处理错误的代码。C++异常处理涉及到三个关键词:try
, catch
和 throw
。
-
throw:当问题出现时,程序会“抛出”一个异常。这是由 throw
关键词完成的。
-
catch:在您希望处理问题的地方,通过 catch
语句块捕获异常。
-
try:try
语句块用于放置可能引发异常的代码。
基本示例
#include <iostream>
int main() {
try {
int divisor = 0;
int dividend = 10;
if (divisor == 0) {
throw "Division by zero condition!";
}
int result = dividend / divisor;
std::cout << "Result: " << result << std::endl;
} catch (const char* e) {
std::cerr << "Error: " << e << std::endl;
}
return 0;
}
在上面的代码中,我们尝试通过零进行除法,这显然是不允许的。因此,我们抛出一个异常,然后在 catch
语句块中捕获并处理它。
使用标准异常
C++ STL中提供了一系列标准的异常类,例如 std::runtime_error
, std::out_of_range
, std::invalid_argument
等。以下是使用标准异常的示例:
#include <iostream>
#include <stdexcept>
int divide(int dividend, int divisor) {
if (divisor == 0) {
throw std::runtime_error("Division by zero condition!");
}
return dividend / divisor;
}
int main() {
try {
int result = divide(10, 0);
std::cout << "Result: " << result << std::endl;
} catch (const std::runtime_error& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
在这个示例中,我们使用 std::runtime_error
来代替字符串异常,并使用 e.what()
方法打印异常消息。
总之,异常处理提供了一种管理程序错误的方法,它允许开发人员将错误处理逻辑与主要的程序逻辑分离开来,使代码更加清晰和有组织。
自定义异常
在C++中,自定义异常通常意味着定义一个新的异常类。这个类通常继承自标准库的异常类,例如 std::exception
。以下是一个如何自定义异常的步骤:
-
定义异常类:创建一个新的类,继承自 std::exception
或其他相关的异常类。
-
提供异常消息:覆盖 what()
函数,这样当异常被捕获并处理时,可以提供一个描述性的错误消息。
-
抛出自定义异常:在代码的适当位置使用 throw
关键字抛出自定义的异常。
-
捕获自定义异常:使用 try-catch
语句块来捕获和处理异常。
以下是一个简单的示例:
#include <iostream>
#include <exception>
// 1. 定义异常类
class MyException : public std::exception {
private:
std::string message;
public:
MyException(const std::string& msg) : message(msg) {}
// 2. 提供异常消息
virtual const char* what() const noexcept override {
return message.c_str();
}
};
int main() {
try {
// 某些条件触发异常
bool condition = true;
if (condition) {
// 3. 抛出自定义异常
throw MyException("This is a custom exception");
}
} catch (const MyException& e) { // 4. 捕获自定义异常
std::cerr << "Caught exception: " << e.what() << std::endl;
} catch (const std::exception& e) {
std::cerr << "Caught standard exception: " << e.what() << std::endl;
}
return 0;
}
上述代码中,我们定义了一个名为 MyException
的自定义异常类,该类提供了一个描述性的错误消息。在 main
函数中,我们抛出了这个异常,并在一个 try-catch
语句块中捕获和处理它。