tags:

views:

68

answers:

2

Following code throws (handled) exceptions, it appears that MVC uses exceptions to test for control locations.

<% Html.RenderPartial("LogOnUserControl"); %>

Application works as expected, I can see that exception is thrown couple times trying different locations (Views, Shared). Same thing happens with other controls. Apparently MVC uses exceptions to probe different possible locations for the file.

IIRC using exceptions for flow control is evil, and is not cool. So, am I doing something wrong, or MVC is cool no more?

Note: having IDE stop on all thrown exception makes debugging easier, and I normally leave it on. That's how I got to that exception from RenderPartial.

+2  A: 

When running in Release mode view locations are cached.

Darin Dimitrov
it makes it less evil, but doesn't explain why would they use exception on the first place. Why would you use `try { file.Open() }` instead of `if (file.Exists)` (I don't know if that's what MVC does, just demonstrating my point)? (No, didn't look at the code yet, still hope SO can answer this).
I don't mind doing it in Debug mode if it is optimized in Release mode. So if you make sure that your views exist (which you should) in Release mode, no searches will be made as the location will be cached and the file directly accessed. Of course if the file is not found or you don't have permissions to read it an exception will be thrown at runtime but that's normal: it's an exceptional case. So I don't see what the problem is. Exceptions are bad when they are thrown often: for example when parsing user input. But in case of view locations an exception will be thrown only if not found.
Darin Dimitrov
Exceptions are bad when are used to indicate non-exceptional condition. Even if it happens once in the life of the universe. Problem is - I get my IDE interrupted on RenderPartial, when I want to debug my code. Problem is that I have to find the exception in the list of exception to disable one thrown by RenderPartial. And most of all, I am curious if there is a reason to use exception instead of if-clause.
@user93422 please see my response that provides more details on why this is happening. It's unfortunate that this impacts debugging but there really is nothing that can be done about it in MVC 3.
marcind
+3  A: 

It is not true that MVC 2.0 uses exceptions for control flow.

However, System.Web.dll v2.0 (the core component of ASP.NET up to .NET 3.5) has some inefficient APIs for instantiating objects from virtual paths. MVC 2.0 mitigates this problem by having a cache of view lookups. By default this cache is disabled during development so that the changes you make are immediately visible, which is why you are seeing these exceptions. On a real production server these exceptions would not occur after the lookups are cached.

As a side note, MVC 3 will be using new APIs added in .NET 4 so this should not be a problem anymore.

marcind