c++ sqrt()函数
自定义异常和逻辑异常的运用
还有运行时异常小编还不是很了解,请大家多多指教
/*===============================================
* 文件名称:myexception.cpp
* 创 建 者:
* 创建日期:2022年09月24日
* 描 述:
================================================*/
#include
#include
#include
#include
using namespace std;
class myexception:public exception
{
public:
myexception(const char*arg)noexcept//为了防止exception类再次抛出异常
{
int len =strlen(arg)+1;
what_arg=new char[len];
strcpy(what_arg,arg);
cout<<__func__<<";"<<__LINE__<<endl;
}
virtual ~myexception()
{
delete[]what_arg;
cout<<__func__<<";"<<__LINE__<<endl;
}
public:
const char*what()const noexcept
{
return what_arg;
}
private:
char *what_arg;
};
float sqrt_num(int x)
{
if(x<0)
{
//invalid_argument obj("error:x<0!");
//throw(obj);
throw (invalid_argument("error:x<0!"));
}
else if(x==0)
{
throw (myexception("error:x==0!"));
}
return sqrt(x);
}
int main ()
{
int x;
cout<<"please input a number:";
cin>>x;
try
{
cout<<"sqrt" <<"("<<x<<")="<<sqrt_num(x)<<endl;
}
catch (invalid_argument &obj)
{
cout <<obj.what()<< endl;
}
catch (myexception &obj)
{
cout <<obj.what()<< endl;
}
cout <<"boyandgirls "<<endl;
return 0;
}
运行结果:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)