PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 5, 2022

[FIXED] How to make parent's Exception throw message defined in child?

 August 05, 2022     c#, exception, inheritance     No comments   

Issue

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."));
    }

Solution

Injecting the exception message into the constructor is one way to do this:

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) { }
}


Answered By - jwdonahue
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing