例:防止除数为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; }
异常处理再例:求三角形周长
#include <iostream> #include <stdexcept> using namespace std; int triangle(int a, int b, int c) { if(a<0 || b<0 || c<0 || a+b<=c || a+c<=b || b+c<=a) throw runtime_error("The lengths of three sides can't form triangle"); return a + b + c; } int main() { int total = 0; try { total = triangle(3,4,7); } catch(const runtime_error& e) { cout<<e.what()<<endl; } cout<<total<<endl; return 0; }
在异常处理中处理析构函数
#include <iostream> #include <string> using namespace std; class Student { public: Student(int n,string nam):num(n), name(nam) { cout<<"constructor-"<<n<<endl; } ~Student( ) { cout<<"destructor-"<<num<<endl; } void get_data( ); private: int num; string name; }; void Student::get_data( ) { if(num==0) throw num; //如num=0,抛出int型变量num else cout<<num<<" "<<name<<endl; cout<<num<<" is in get_data()!"<<endl; } void fun( ) { Student stud1(1101,"Tan"); stud1.get_data( ); Student stud2(0,"Li"); stud2.get_data( ); } int main( ) { try { fun( ); } catch(int n) { cout<<"num="<<n<<",error!"<<endl; } return 0; }
在函数嵌套的情况下检测异常处理
#include <iostream> using namespace std; int main( ) { void f1( ); try { f1( ); //调用f1( ) } catch(double) { cout<<"OK0!"<<endl; } cout<<"end0"<<endl; return 0; } void f1( ) { void f2( ); try { f2( ); //调用f2( ) } catch(char) { cout<<"OK1!"; } cout<<"end1"<<endl; } void f2( ) { void f3( ); try { f3( ); //调用f3( ) } catch(int) { cout<<"Ok2!"<<endl; } cout<<"end2"<<endl; } void f3( ) { double a=0; try { throw a; //抛出double类型异常信息 } catch(float) { cout<<"OK3!"<<endl; } cout<<"end3"<<endl; }
时间: 2024-09-22 07:22:27