一个典型的问题程序
#include <iostream> using namespace std; template <typename T> T Div(T x,T y) { return x/y; } int main() { int x,y; double x1,y1; cin>>x>>y; //y要是输入0,就玩完了 cin>>x1>>y1; //同上 cout<<x<<"/"<<y<<"="<<Div(x,y)<<endl; cout<<x1<<"/"<<y1<<"="<<Div(x1,y1)<<endl; return 0; }
再不用担心意外带来的不快了!
#include <iostream> using namespace std; template <typename T> T Div(T x,T y) { if(y==0) throw y;//抛出异常 return x/y; } int main() { int x=5,y=0; double x1=5.5,y1=0.0; try { //被检查的语句 cout<<x<<"/"<<y<<"="<<Div(x,y)<<endl; cout<<x1<<"/"<<y1<<"="<<Div(x1,y1)<<endl; } catch(int)//异常类型 { cout<<"除数为0,计算错误!"<<endl;//异常处理语句 } catch(double)//异常类型 { cout<<"除数为0.0,计算错误!"<<endl;//异常处理语句 } return 0; }