第18章 - 异常处理
嗨,朋友!我是长安。
异常处理用于处理程序运行时的错误,让程序更健壮。
⚠️ try-catch基础
#include <iostream>
using namespace std;
int divide(int a, int b) {
if (b == 0) {
throw "除数不能为0!"; // 抛出异常
}
return a / b;
}
int main() {
try {
int result = divide(10, 0);
cout << "结果:" << result << endl;
} catch (const char* msg) {
cout << "错误:" << msg << endl;
}
cout << "程序继续运行..." << endl;
return 0;
}
🎯 自定义异常类
class DivideByZeroException {
private:
string message;
public:
DivideByZeroException(string msg) : message(msg) {}
string what() { return message; }
};
int safeDivide(int a, int b) {
if (b == 0) {
throw DivideByZeroException("除数为零!");
}
return a / b;
}
int main() {
try {
int result = safeDivide(10, 0);
} catch (DivideByZeroException& e) {
cout << "异常:" << e.what() << endl;
}
}
