- assert在debug模式可以使用,可以通过#define NDEBUG使得assert不起作用
- try
- {
- throw
- }
- catch
- {
- }
- 三者缺一不可
10.throw抛出的可以是基本类型,也可以是自定义类型 - #include
#define NDEBUG//禁用assert断言,assert在release下面不起作用
#include <assert.h>
#include
using namespace std;
class Student
{
};
double devide(double x, double y)
{
if (y == 0)
{
throw y;
}
return x / y;
}
class myERROR
{
public:
myERROR(string str):myerror(str){}
string what()
{
return myerror;
}
private:
string myerror;
};
class A
{
public:
explicit A(int i=5,int j=10)
{
num = i;
mb = j;
}
void display()
{
cout << num<<" "<<mb<< endl;
}
private:
int num;
int mb;
};
void coutMy( const char *ch)//无法使用string &ch
{
cout << ch << endl;
}
int main()
{
Student *s = nullptr;
assert(s != nullptr);
cout << 123456 << endl;
cout << “----------------------” << endl;
try
{
double res = devide(2, 3);
cout << res << endl;
res = devide(4, 0);
cout << res << endl;
}
catch (...)
{
cerr << "error of diviing zero.\n";
//exit(1);
}
cout << "----------------------" << endl;
int x = 0;
try
{
if (x == 0)
{
throw myERROR("x===0");
}
}
catch (myERROR &myserror)
{
cout << myserror.what() << endl;
}
cout << "----------------------" << endl;
A a;
//a = 100;y由于加了explicit,不可以隐式转换
a.display();
cout << "----------------------" << endl;
coutMy("789456");
cout << "----------------------" << endl;
system("pause");
return 0;
}