(此文中代码示例来着 中国大学生mooc中北大的周韦 老师)
#include <iostream> using namespace std; int main() { double m, n; cin >> m >> n; try { cout << "before dividing" << endl; if( n == 0) //抛出个整形数异常i,而且,通过throw 抛出 try 的函数外面去 throw -1; else if( m == 0) //抛出个浮点数异常, 通过throw 抛到函数外面去 throw -1.000; else cout << m/n << endl; cout << "after diving" << endl; } // catch 函数通过抛出的数据来重载, 确认错误的原因 并 输出 catch(double d) { cout << "catch(double)" << d << endl; } catch(int d) { cout << "catch(int)" << d << endl; } cout << "finished" << endl; }
一般抛出异常后,我们很难提前编写正确的函数去处理它, 所以我们一般只抛出错误信息的字符串,然后根据字符串来 编写正确的处理函数。
c++ 标准异常
在c++标准库中定义了不少的 处理异常的函数,未完待续
这只是 异常处异的最简便版本,以后会补上 较为复杂,实用的异常处理。
作为个人笔记, 还请各位大佬海涵