欢迎来到程序员中文网!

首页 Linux Mysql C++ Python PHP JavaScript 资源下载 动态 开源推荐
我要投稿 投诉建议

C++ 调试与错误处理:异常与断言

时间:2026年08月12日 05:34:29 浏览:0

C++ 调试与错误处理:异常与断言


异常和断言是 C++ 中主要的错误处理机制。


1. 异常处理(try/catch)


try {
if (condition) {
throw std::runtime_error('Something went wrong');
}
} catch (const std::exception& e) {
std::cerr << 'Error: ' << e.what() << std::endl;
} catch (...) {
std::cerr << 'Unknown error' << std::endl;
}

2. 自定义异常


class MyException : public std::exception {
public:
const char* what() const noexcept override {
return 'My custom exception';
}
};

3. 断言(assert)


用于调试阶段检测逻辑错误。


#include <cassert>
int divide(int a, int b) {
assert(b != 0 && 'Division by zero');
return a / b;
}

NDEBUG 宏定义时断言被禁用,适合发布版本。


4. 静态断言(static_assert)


编译期断言,检测类型属性等。


static_assert(sizeof(int) == 4, 'int must be 4 bytes');

合理使用异常和断言能提高代码健壮性。