我正在dotnet core上创建一个Web api应用程序,尝试捕获异常,但是它不起作用
using Microsoft.AspNetCore.Mvc;
using System;
namespace WebApplication1.Controllers
{
public class TestModel
{
public long Num { get; set; }
public decimal TotalCost { get; set; }
public decimal Avg => Math.Round(TotalCost / Num, 4);
}
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult<TestModel> Get()
{
return new TestModel { Num = 0, TotalCost = 1 };
}
}
}
我希望输出一个异常,但它显示正常
答案 0 :(得分:2)
在您调用.Avg:_ = l.Avg;
之前,它不会引发异常,因此实际的代码将被触发并抛出DivideByZeroException
异常。
[HttpGet]
public ActionResult<TestModel> Get()
{
var l = new TestModel { Num = 0, TotalCost = 1 };
_ = l.Avg;
return l;
}