c++异常
#include <iostream>
#include <string>
#include <string.h>
#include <stdlib.h>
using namespace std;
int mydive(int a, int b)
{
if(b == 0)
throw 1; // 处理异常 抛出异常 抛出一个类型
return a / b;
}
void test01()
{
// 尝试捕获异常
try
{
mydive(2,0);
}
catch(int)
{
cout << "int error"<< endl;
}
}
int main()
{
test01();
return 0;
}
编写自己的异常类
#include <iostream>
#include <string>
#include <string.h>
#include <stdlib.h>
using namespace std;
class Longlongerror:public exception
{
public:
Longlongerror(string data)
{
this->data = data;
}
Longlongerror(char * data)
{
this->data = data;
}
virtual const char * what() const throw()
{
return data.c_str();
}
string data;
};
void fun()
{
throw Longlongerror("changchang error");
}
void test01()
{
try
{
fun();
}
catch (exception &p)
{
cout << p.what() <<endl;
}
}
int main()
{
test01();
return 0;
}