异常处理机制允许程序在异常情况发生时优雅地终止或恢复。c++++ 中的异常处理流程包括:使用 throw 语句引发异常。未处理的异常会导致程序终止。自定义异常类可派生自 std::exception 或 std::runtime_error。使用 std::terminate 手动终止程序。实战案例中,文件处理时若文件打开失败,则抛出异常并按照错误处理流程执行。

异常处理
异常处理机制允许程序在发生异常情况时进行优雅地终止或恢复。C++ 中的异常处理使用异常对象表示异常情况。
异常引发
异常使用 throw 语句引发:
throw std::exception();
这会抛出一个对象为 std::exception 的异常。
异常终止
没有使用 catch 子句处理的异常会导致程序终止:
int main() {
throw std::exception();
} 输出:
terminate called without an active exception Aborted
异常终止 with 非 std::exception 对象
自定义异常类可以派生自 std::exception 或 std::runtime_error:
class MyException : public std::runtime_error {
public:
MyException() : std::runtime_error("My Exception") {}
}; 可以使用 std::terminate 手动终止程序:
void func() {
throw MyException();
}
int main() {
try {
func();
} catch (const MyException& e) {
std::cout << e.what() << std::endl;
std::terminate();
}
} 输出:
My Exception terminate called after throwing an instance of 'MyException' what(): My Exception Aborted
实战案例:文件处理
#include <fstream>
void readFile(const std::string& filename) {
std::ifstream file(filename);
if (!file.is_open()) {
throw std::runtime_error("Cannot open file: " + filename);
}
// ...
}
int main() {
try {
readFile("invalid_file.txt");
} catch (const std::runtime_error& e) {
std::cout << e.what() << std::endl;
return 1;
}
// ...
} 输出:
Cannot open file: invalid_file.txt
以上就是C++函数异常处理引发与终止的深入探究的详细内容,更多请关注知识资源分享宝库其它相关文章!







发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。