如何使父母在孩子中定义的例外抛出消息?
当我得到它时,由于异常被抛在父级中,因此该消息的定义是在parent -null中定义的(system.exception:“ exception_wasthrown”
,message:“类型'system的异常。例外“被抛出。”)。如何解决这个问题?
计划,粗略:
internal abstract class Figure
{
protected string BadFigExceptionMessage { get; set; }
public Figure(params int[] measurements)
{
if (measurements.Any(x => x<=0)) throw new Exception(BadFigExceptionMessage);
}
}
class Triangle : Figure
{
public Triangle(params int[] sides) : base(sides)
{
BadFigExceptionMessage = "Such a triangle does not exist.";
}
}
我对Nunit的测试:
[Test]
[TestCase(-2, -2, -6)]
[TestCase(0, 0, 0)]
public void CalculateSquareOf_ImpossibleTriagSides_ReturnExceptionNoSuchTriag(int a, int b, int c)
{
Exception ex = Assert.Throws<Exception>(() =>
SquareCalculatorLib.Calculator.CalculateSquareOf(a, b, c)); //involves the Triangle constructor
Assert.That(ex.Message, Is.EqualTo("Such a triangle does not exist."));
}
As I get it, since the Exception is thrown in the parent, the message is as it is defined in parent - null (System.Exception: "Exception_WasThrown"
, message: "Exception of type 'System.Exception' was thrown."). How to work around this issue?
Program, roughly:
internal abstract class Figure
{
protected string BadFigExceptionMessage { get; set; }
public Figure(params int[] measurements)
{
if (measurements.Any(x => x<=0)) throw new Exception(BadFigExceptionMessage);
}
}
class Triangle : Figure
{
public Triangle(params int[] sides) : base(sides)
{
BadFigExceptionMessage = "Such a triangle does not exist.";
}
}
My test with NUnit:
[Test]
[TestCase(-2, -2, -6)]
[TestCase(0, 0, 0)]
public void CalculateSquareOf_ImpossibleTriagSides_ReturnExceptionNoSuchTriag(int a, int b, int c)
{
Exception ex = Assert.Throws<Exception>(() =>
SquareCalculatorLib.Calculator.CalculateSquareOf(a, b, c)); //involves the Triangle constructor
Assert.That(ex.Message, Is.EqualTo("Such a triangle does not exist."));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将异常消息注入构造函数是一种方法:
Injecting the exception message into the constructor is one way to do this: