The title pretty much says it but here is some background:
I have an ASP.Net MVC application where I need to check a list of file paths for existence. If any of the paths do not exist then an error is returned.
Presently, I have a base controller where the OnException event is implemented. Here, any unhanded exceptions are dealt with and an error page is returned to the user with the exception's message.
The simplest way for me to do the above check is to write a method that checks each path for existence and if any of them fail, I simply throw (and log) an exception. This exception is then handled by the base controller and the appropriate message is returned to the user.
My problem is that doing this feels like bad practice. I am writing a method that returns void and its only purpose is to throw an exception in the rare case that one of the paths does not exist, in most cases it does nothing. Is this a bad idea?
It is good practice to throw exceptions if you have appropriate exception handling. Don't blindly throw exceptions until the application crashes. In your option 1 example, an ArgumentException is more appropriate. Your option 2 is more appropriate for data validations.
Yes, throwing an exception causes the method to return immediately. However, it's not a normal return. For example, there is no return value. The only way to capture control from a method that is returning as a result of an exception being thrown, is to have an exception handler.
Exceptions should be thrown when the contract between a method and its caller cannot be fulfilled. This is the usage identified in the Java™ Language Specification.
There is nothing wrong with that.
The .NET framework does this too: for example, CancellationToken
has a method ThrowIfCancellationRequested
which does nothing but throw or not throw depending on some condition.
Another example: Dispatcher
's VerifyAccess
method, which checks if the caller is on the same thread as the control is supposed to be accessed on, and throws if not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With