在C++中,异常处理是一种处理运行时错误(如内存分配失败、无效的用户输入等)的机制。它允许程序在出现错误时优雅地处理,而不是简单地崩溃。异常处理的核心组件是try
、catch
和throw
。
-
throw:这是用来抛出异常的语句。当某个函数检测到无法处理的错误时,它会使用
throw
语句抛出一个异常。这个异常可以是任何数据类型,但通常我们使用特定的异常类型(如std::runtime_error
或自定义的异常类)。
cpp复制代码
if (/* some error condition */) { | |
throw std::runtime_error("An error occurred!"); | |
} |
-
try:
try
块包含可能抛出异常的代码。在try
块中,你可以编写可能引发异常的代码,而不必担心如何处理这些异常。
cpp复制代码
try { | |
// Code that might throw an exception | |
} |
-
catch:
catch
块用于捕获并处理try
块中抛出的异常。你可以指定catch
块要捕获的异常类型。当try
块中的代码抛出异常时,C++运行时会查找与异常类型匹配的catch
块,并执行该块中的代码。
cpp复制代码
try { | |
// Code that might throw an exception | |
} catch (const std::runtime_error& e) { | |
// Handle the exception | |
std::cerr << "Caught an exception: " << e.what() << '\n'; | |
} |
注意,你可以有多个catch
块来捕获不同类型的异常,但它们的顺序很重要。更具体的异常类型(即继承层次结构中的子类)应该放在更一般的异常类型之前。这样,当抛出特定类型的异常时,C++会先查找与该类型匹配的catch
块。
另外,还有一个特殊的catch
块可以捕获所有类型的异常,它的形式为catch(...)
。这种catch
块通常用于记录错误或执行一些清理操作,然后重新抛出异常,以便其他代码可以处理它。
cpp复制代码
try { | |
// Code that might throw an exception | |
} catch (const std::runtime_error& e) { | |
// Handle runtime_error exceptions | |
} catch (...) { | |
// Handle all other exceptions | |
std::cerr << "Caught an unknown exception\n"; | |
throw; // Re-throw the exception | |
} |