0
点赞
收藏
分享

微信扫一扫

C++从入门到精通——异常处理


  • 捕捉异常
  • throw: 问题出现时,抛出异常
  • catch:用于捕捉异常
  • try:标识即将被激活的异常

#include <iostream>
using namespace std;
double division(int a,int b){
if(b==0){
throw "除数不能为0";
}
return a/b;
};

int main(){

int x=50;
int y = 0;
double z = 0;
try {
z = division(x,y);
cout<<"z is :"<<z<<endl;
}// 抛出指定的异常
catch (const char* msg){
cerr<<msg<<endl;
}catch (const exception e){
return 0 ;
}
return 0;
}

C++从入门到精通——异常处理_exception

  • 自定义异常

#include <iostream>
#include <exception>
using namespace std;
double division(int a,int b){
if(b==0){
throw "除数不能为0";
}
return a/b;
};

struct MyException:public exception{

const char *what () const throw(){
return "C++ Exception";
}

};
int main(){

int x=50;
int y = 0;
double z = 0;
try {
throw MyException();
}catch(MyException& e){
cout<<e.what()<<endl;
}


try {
z = division(x,y);
cout<<"z is :"<<z<<endl;
}// 抛出指定的异常
catch (const char* msg){
cerr<<msg<<endl;
}catch (const exception &e){
return 0 ;
}
return 0;
}

C++从入门到精通——异常处理_自定义异常_02


举报

相关推荐

0 条评论