How to ignore DivideByZeroException in Razor views

961 views Asked by At

RazorEngine is used to run C# Razor views in ASP.NET MVC4 application.

Views contain decimal expressions wrapped to custom Format function call like

<div>@Format(somedecimalexpression/someotherdecimalexpression)</div>

This causes exception

Attempted to divide by zero

if someotherdecimalexpression value is 0

How to force razor engine to ignore division by zero exception? It can return big decimal number or null on empty string if this occurs.

Expressions are created by end users at runtime. Database fields have decimal type and it is difficult to convert all operands to double to remove this exception.

Check for artihmetic overflow is unchecked in project properties but this does not help. I tried

<div>@Eval("somedecimalexpression/0")</div>

and in template base class

public string Eval(string expression) {

try {

  return Format(Run(expression));
}
catch (DivideByZeroException) {
  return ""
}

}

but got compile error since there is not Run method.

2

There are 2 answers

0
Christoph Fink On BEST ANSWER

If you know the name of someotherdecimalexpression at runtime you could do the following:

string name = "someotherdecimalexpression";
template = template.Replace(name, "(double)" + name);

This will convert all someotherdecimalexpression to double for the calculation and you get Infinity instead of an exception.

But be aware of the "side effects" like if the name is something which could also be used e.g. "in text"...

1
Matt Bodily On

I agree with Uriil's comment. If you still want the logic on the view you can get around the error using an if

<div>
    @if(someotherdecimalexpression != 0){
        Format(somedecimalexpression/someotherdecimalexpression)
    }
</div>