#include<iostream> using namespace std; void testfun(int age) { try { if(age<0) throw"请输入学生年龄必须是整数"; if(age>20) throw age; cout<<"年龄正常学生年龄是"<<age<<endl; } catch (int i) { cout<<"发生异常:学生年龄太大"<<endl; } catch(const char *message)//cosnt 牢记const char { cout<<"发生异常"<<message<<endl; } } int main() { testfun(12); testfun(-9); testfun(77); return 0;
}
排错机制直接打进函数里面
或者 函数里面只有抛出异常
而 try catch main里面调用
#include <iostream> using namespace std; double div(double a,double b) { if(b==0) throw b; return a/b; } int main() { double x,y,result; cout<<"input two numbers:"<<endl; while(cin>>x>>y) { try { result=div(x,y); cout<<x<<"/"<<y<<"="<<result<<endl; } catch(double) { cout<<"error"<<endl; } cout<<"input two numbers:"<<endl; } return 0; }