Avoid Using Exceptions as Control Flows

Giulliano Bueno
2 min readNov 21, 2023

--

Spaghetti code

Using exceptions as a control flow mechanism in Rails API controllers is generally discouraged for several reasons.

class Api::BookingsController

def create
...
rescue ProductNotAvailable
product_not_available
end

private

def product_not_available
render_error(400, "Product unavailable")
end
end

Performance

Exceptions are computationally expensive compared to regular control flow mechanisms. Throwing and catching exceptions involves additional overhead, impacting the performance of your application. In performance-sensitive code paths, relying on exceptions for control flow can lead to inefficiencies.

Clarity

Exception handling is typically used for exceptional situations, such as errors or unexpected conditions. Using exceptions for regular control flow can make the code less readable and harder to understand. It may lead to confusion for developers who expect exceptions to signify error scenarios.

Intent

Exceptions are designed to handle exceptional flow and error conditions, not as a mechanism for regular program flow. Relying on exceptions for control flow can violate the principle of least astonishment, making the codebase harder to maintain and extend.

Debuggability

When exceptions are used for control flow, it can complicate debugging. Developers may need to trace through the stack to understand the normal flow of the program, and debugging tools might not work as effectively when exceptions are thrown and caught routinely.

Maintainability

Code that uses exceptions for control flow can be harder to maintain and modify. It may be more challenging to reason about the program’s behavior and make changes without introducing unintended side effects.

Instead of using exceptions for control flow, consider using more explicit and conventional constructs such as conditional statements, loops, and other control flow mechanisms provided by the programming language. This can lead to more readable, maintainable, and performant code in the long run.

In Rails, controllers typically handle requests and responses, and using exceptions for control flow within this context can make the code harder to follow for other developers who expect exceptions to represent error conditions rather than regular flow control. It’s generally recommended to reserve exceptions for exceptional cases and error handling, and use standard control flow constructs for regular program flow.

--

--