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?
There is nothing wrong with that.
The .NET framework does this too: for example,
CancellationTokenhas a methodThrowIfCancellationRequestedwhich does nothing but throw or not throw depending on some condition.Another example:
Dispatcher‘sVerifyAccessmethod, which checks if the caller is on the same thread as the control is supposed to be accessed on, and throws if not.