Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is is bad practice to write a method that does nothing except throw an exception?

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?

like image 653
zaq Avatar asked Jan 05 '12 00:01

zaq


People also ask

Is it bad practice to throw exceptions?

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.

Does throwing an exception return from a method?

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.

Is it good to throw exception in Java?

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.


1 Answers

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.

like image 143
Roman Starkov Avatar answered Oct 03 '22 10:10

Roman Starkov