Raising generic string messages as exceptions creates several problems that make code harder to maintain and test.
When you use raise "message"
, Ruby automatically wraps the string in a RuntimeError
. This means all your different error
conditions become indistinguishable RuntimeError
exceptions. Your calling code cannot handle different types of errors appropriately.
For example, you might want to retry on network errors but immediately fail on validation errors. With generic string exceptions, this becomes
impossible because both errors look the same to exception handlers.
Testing also becomes problematic. Your tests must catch the generic RuntimeError
class, which means they cannot verify that the right
type of error occurred. This makes tests less precise and more likely to pass when they should fail.
Using specific exception classes solves these problems. Each error condition gets its own class, making error handling more precise. Tests can
verify the exact type of exception, improving test reliability. Code becomes more self-documenting because exception names clearly indicate what went
wrong.
What is the potential impact?
Using generic string exceptions reduces code maintainability and makes error handling imprecise. Tests become less reliable because they cannot
distinguish between different error conditions. This can lead to bugs being missed in testing and inappropriate error handling in production code.