c++中异常的简单处理 发表于 2018-01-15 | | 阅读次数 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384#include <iostream>#include <string.h>using namespace std;//标识错误的类型void wrong (){};int intdiv(int a, int b){ try { if (b==0) { throw 10;//可以是任何对象 ,也可以throw一个函数wrong(); } int c = a / b; return c; } catch (int data )//类型名,catch的参数捕获的是throw的东西 { cout << "除法异常已经处理"; return -1; }}int intdivA(int a, int b){ return a / b;}void main(){ int x, y; cin >> x >> y; try { if (y==0) { throw "被除数为0"; } else if (x==0) { throw "除数为0"; } } catch (const char * s)//catch 捕获的是throw的东西,throw字符串的时候,捕获也要捕获字符串进行相应处理 { if (strcmp(s,"被除数为0")==0) { cout << "被除数为0异常,请重新输入"; cin >> x >> y; } else if (strcmp(s, "除数为0") == 0) { cout << "除数为0异常,请重新输入"; cin >> x >> y; } } std::cout << intdiv(x, y); cin.get(); cin.get(); cin.get();} 坚持原创技术分享,您的支持将鼓励我继续创作! 赏 微信打赏 支付宝打赏