I tried the following code:
if (vm.SubmitAction == "Delete")
{
throw new DivideByZeroException(); // LOCATION A
return View();
accountTable.Delete(vm.Account);
}
if (Session["CurrentUrl"] != null ) // LOCATION B
{
Clicking on Delete takes me to LOCATION A.
When I then step through using F11 it goes next to LOCATION B and then raises and exception:
System.DivideByZeroException was unhandled by user code
Message=Attempted to divide by zero.
Can someone explain why it does not go to the return View() or simply exit the action?
Exceptions are just that. Exceptions. Something didn’t go as planned. And the method can therefore not continue as planned. Instead, the application travels up the call stack to find a catch block that will take care of the exception. If no catch block is found, the application crashes.
MVC got a build in attribute used to handle errors. It’s called
[HandleError]. But it does not let the action continue, but it prevents ASP.NET from showing the yellow screen.A typical try/catch in post actions looks like this:
You can read more about errors in MVC in my blog.