如何在子项中定义父项的异常抛出消息?
How to make parent's Exception throw message defined in child?
据我了解,由于异常是在父级中抛出的,因此消息与在父级中定义的一样 - null (System.Exception: "Exception_WasThrown"
, message: "Exception of type 'System.Exception' was thrown ”)。如何解决此问题?
程序,大致:
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."));
}
将异常消息注入构造函数是一种方法:
internal abstract class Figure
{
public Figure(string exMsg, params int[] measurements)
{
if (measurements.Any(x => x <= 0)) throw new Exception(exMsg);
}
}
class Triangle : Figure
{
public Triangle(int a, int b, int c) : base("Such a triangle does not exist.", a, b ,c) { }
}
据我了解,由于异常是在父级中抛出的,因此消息与在父级中定义的一样 - null (System.Exception: "Exception_WasThrown"
, message: "Exception of type 'System.Exception' was thrown ”)。如何解决此问题?
程序,大致:
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."));
}
将异常消息注入构造函数是一种方法:
internal abstract class Figure
{
public Figure(string exMsg, params int[] measurements)
{
if (measurements.Any(x => x <= 0)) throw new Exception(exMsg);
}
}
class Triangle : Figure
{
public Triangle(int a, int b, int c) : base("Such a triangle does not exist.", a, b ,c) { }
}