在 c++++ 中,异常通过 try-catch 语句处理:try 块中代码可能抛出异常。catch 块捕获标准异常或自定义异常。noexcept 关键字声明函数不会抛出异常,以进行优化。

C++ 函数中如何处理异常?
在 C++ 中,异常通过 try-catch 语句处理,包括三个主要部分:
try {
// 代码块,可能抛出异常
}
catch (const std::exception& e) {
// 捕获标准异常
}
catch (const MyCustomException& e) {
// 捕获自定义异常
}实战案例:
立即学习“C++免费学习笔记(深入)”;
假设我们有一个函数 divide,它计算两个数的商,但当分母为 0 时抛出异常:
int divide(int num, int denom) {
try {
if (denom == 0) {
throw std::runtime_error("除数不能为 0");
}
return num / denom;
}
catch (const std::exception& e) {
std::cout << "错误: " << e.what() << std::endl;
}
}在主函数中,我们可以调用 divide 函数并捕获异常:
int main() {
try {
int dividend = 10;
int divisor = 0;
int result = divide(dividend, divisor);
std::cout << dividend << " / " << divisor << " = " << result << std::endl;
}
catch (const std::runtime_error& e) {
std::cout << e.what() << std::endl;
}
}输出:
错误: 除数不能为 0
注意:
std::exception。noexcept 关键字声明函数不会抛出异常,以进行优化。以上就是C++ 函数中如何处理异常?的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号