当我输入1,-1测试的时候,为什么最后没有输出A类中what()方法的字符串:"A故障"?
源码以及运行结果如下,请大手子指导,不胜感激!
#include <iostream>
#include <exception>
#include <cmath>
using namespace std;
float test1(float a,float b){
return 2*a*b/(a+b); //a==-b时会引发故障
}
float test2(float a,float b){
return sqrt(a*b); // a*b<0时会引发故障
}
class A: public std::exception
{
public:
virtual const char* what() {
return "A故障";
}
A():std::exception(){} //继承类的构造函数必用初始化列表
};
class B:public std::exception
{
public:
virtual const char* what() {
return "B故障";
}
B():std::exception(){}
};
int main(){
int a,b;
cout<<"输入a,b的值"<<endl;
cin>>a;
cin>>b;
try{
if(a!=-b){
cout<<" test1(a,b) = "<<test1(a,b)<<endl;
}
else{
A aa; // aa是类A用默认构造函数创建的对象
throw aa;//抛出异常对象aa
}
if(a*b>0){
cout<<" test2(a,b) = "<<test2(a,b)<<endl;
}
else{
B bb;
throw bb;
}
}
//catch捕获异常
catch(std::exception& k){
cout<< k.what();
}
return 0;
}
源码以及运行结果如下,请大手子指导,不胜感激!
#include <iostream>
#include <exception>
#include <cmath>
using namespace std;
float test1(float a,float b){
return 2*a*b/(a+b); //a==-b时会引发故障
}
float test2(float a,float b){
return sqrt(a*b); // a*b<0时会引发故障
}
class A: public std::exception
{
public:
virtual const char* what() {
return "A故障";
}
A():std::exception(){} //继承类的构造函数必用初始化列表
};
class B:public std::exception
{
public:
virtual const char* what() {
return "B故障";
}
B():std::exception(){}
};
int main(){
int a,b;
cout<<"输入a,b的值"<<endl;
cin>>a;
cin>>b;
try{
if(a!=-b){
cout<<" test1(a,b) = "<<test1(a,b)<<endl;
}
else{
A aa; // aa是类A用默认构造函数创建的对象
throw aa;//抛出异常对象aa
}
if(a*b>0){
cout<<" test2(a,b) = "<<test2(a,b)<<endl;
}
else{
B bb;
throw bb;
}
}
//catch捕获异常
catch(std::exception& k){
cout<< k.what();
}
return 0;
}