- 捕捉异常
- 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;
}
- 自定义异常
#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;
}