How do I fix a DivideByZeroException

526 Views Asked by At

I am using DevExpress XAF Framework.

I have a Class with a lot of Persistent Alias Attributes that does some math on the properties. Here is an example of my code:

[PersistentAlias("ShortTermDebt + LongTermDebt / EquityTotal")]
public decimal DebtEquity
{
    get
    {
        return decimal.Parse(EvaluateAlias("DebtEquity").ToString());
    }
}

I have tried setting the Property to = 1

return DebtEquity = 1;

But all this does is reset the property to 1 on saving.

I have tried setting the Default Value in SQL Server for each property to 1. But this does not work either.

Basically, I have a Detailview that has a bunch of calculations on it. And when I want to create a NEW Detail View, I get a DivideByZeroException because of course a NEW Detail View/Object is not going to have any values. Any ideas how I can get around this?

2

There are 2 best solutions below

1
On BEST ANSWER

If you can get the value of EquityTotal then you can check it for zero first, otherwise you can catch the exception.

Example with check value first:

[PersistentAlias("ShortTermDebt + LongTermDebt / EquityTotal")]
public decimal DebtEquity
{
    get
    {
        if (EquityTotal == 0) return 0;  // return 0 or whatever number you want when EquityTotal is equal to zero
        return decimal.Parse(EvaluateAlias("DebtEquity").ToString());
    }
}

Example with catch exception:

[PersistentAlias("ShortTermDebt + LongTermDebt / EquityTotal")]
public decimal DebtEquity
{
    get
    {
        try
        {
            return decimal.Parse(EvaluateAlias("DebtEquity").ToString());
        }
        catch (DivideByZeroException)
        {
            return 0;  // return 0 or whatever number you want when EquityTotal is equal to zero
        }
    }
}
0
On

As an alternative using pure criteria language syntax, you can use:

[PersistentAlias("Iif(EquityTotal > 0,ShortTermDebt+LongTermDebt/EquityTotal, 0)")]
public decimal DebtEquity
{
    get => Convert.ToDecimal(EvaluateAlias(nameof(DebtEquity)))
}