C++异常处理机制通过try、catch和throw关键词来管理程序运行中错误
主要有同步异常(如运行时错误)和异步异常(如外部事件)两种类型
同步异常
捕获运行时错误
- 示例, 除零异常
#include <iostream>
#include <stdexcept>
void Divide(int a, int b) {
if (b == 0) throw std::runtime_error("division by zero!");
std::cout << "result: " << a / b << std::endl;
}
int main() {
try {
Divide(10, 0);
} catch (const std::runtime_error& e) {
std::cerr << "error: " << e.what() << std::endl;
}
return 0;
}
异步异常
捕获外部事件
- 示例, 文件未找到异常
#include <iostream>
#include <fstream>
#include <stdexcept>
void OpenFile(const std::string& filename) {
std::ifstream file(filename);
if (!file) throw std::runtime_error("File not found!");
}
int main() {
try {
OpenFile("nonexistent.txt");
} catch (const std::runtime_error& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
- 示例, 输入字符串, 若其为数字且小于10000且为偶数则为合法状态, 其他为非法状态
#include <iostream>
#include <cmath>
bool JudgeNumber(std::string s) {
if (s.size() > 5) {
throw "长度超长";
}
int sum = 0;
for (int i = 0, size = s.size(); i < size; i++) {
int v = s[i] - '0';
if (v < 0 || v >9) {
throw "该字符串非数字";
}
sum += (v * pow(10, size - i - 1));
}
if (sum > 10000) {
throw "数字值大于10000";
}
if (sum & 1) {
throw "该数字不为偶数";
}
return true;
}
int main() {
std::string s = "1";
try {
if (JudgeNumber(s)) {
std::cout << s << "是一个合法数字字符串" << std::endl;
}
}
catch (const char* msg) {
std::cout << s << "不是一个合法数字字符串" << std::endl;
std::cerr << "错误原因:" << msg << std::endl;
}
return 0;
}
- 示例, 除法异常
#include <iostream>
#include <cstdlib>
double Divide(double x, double y) {
if (y == 0) {
// 除数为0, 抛出异常
throw y;
}
return x / y;
}
int main() {
double res;
try {
res = Divide(2, 3);
// The result of x/y is:0.666667
std::cout << "The result of x/y is:" << res << std::endl;
res = Divide(4, 0);
}
catch (double) {
// Error of dividing zero.
std::cerr << "Error of dividing zero." << std::endl;
exit(1);
}
return 0;
}