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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Assert 是 Spring 框架提供的一个断言工具类,用于在程序运行中进行断言判断,如果断言条件不满足,则会抛出异常。但是 Spring Assert 只提供了一些基本的断言方法,如果我们需要进行更加个性化的断言判断,可以通过自定义异常来实现。 自定义异常可以继承自 Spring 的 AbstractThrowableAssert 类,并重写其 fail 方法。在自定义异常中,我们可以根据需求定义不同的异常类型,例如业务异常、参数异常等,并在 fail 方法中指定不同的异常信息。 下面以一个示例来说明如何使用和自定义 Spring Assert 异常: ```java public class CustomAssert extends AbstractThrowableAssert<CustomAssert, Object> { private CustomAssert(Object actual, Class<?> selfType) { super(actual, selfType); } public static CustomAssert assertThat(Object actual) { return new CustomAssert(actual, CustomAssert.class); } public CustomAssert isPositiveNumber() { isNotNull(); if (!(actual instanceof Number) || ((Number) actual).doubleValue() <= 0) { failWithMessage("Expected positive number, but found: %s", actual); } return this; } } ``` 在自定义的 CustomAssert 类中,我们通过继承 AbstractThrowableAssert 类,并实现自己的断言方法 isPositiveNumber。在该方法中,我们首先调用 isNotNull 方法来判断输入值是否为空,然后再进行我们的特定判断,如果判断不成立,就通过 failWithMessage 方法抛出异常。 通过自定义异常,我们可以根据业务需求实现更加具体化的断言功能,并在断言失败时提供更加详细的异常信息。在使用自定义断言时,只需要调用 assertThat 方法来创建 CustomAssert 对象,并链式调用不同的断言方法即可。 总的来说,Spring Assert 的自定义异常能够帮助我们实现更加灵活和个性化的断言判断,提高代码的可读性和可维护性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值