assert和异常的使用

  1. assert在debug模式可以使用,可以通过#define NDEBUG使得assert不起作用
  2. try
  3. {
  4. throw
  5. }
  6. catch
  7. {
  8. }
  9. 三者缺一不可
    10.throw抛出的可以是基本类型,也可以是自定义类型
  10. #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;

}


版权声明:本文为weixin_41157881原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。