🚀 KesslerTech

Why is it bad style to rescue Exception  e in Ruby

Why is it bad style to rescue Exception e in Ruby

📅 | 📂 Category: Ruby

Rescuing Objection => e successful Ruby is a communal pattern amongst learners, however it’s thought-about atrocious kind by skilled builders. Wherefore? Due to the fact that it’s similar utilizing a nett with holes truthful large that equal sharks tin aquatics done. You mightiness deliberation you’re catching each the errors, however captious scheme failures might gaffe correct by, leaving your exertion susceptible. This article dives into the causes wherefore this wide objection dealing with is problematic and provides champion practices for strong mistake direction successful your Ruby initiatives.

The Risks of Catching Every part

Rescuing Objection catches each exceptions, together with these supposed to halt execution, similar SystemExit, Interrupt, and NoMemoryError. Ignoring these indicators tin pb to unpredictable behaviour, assets leaks, and trouble successful debugging. Ideate attempting to gracefully unopen behind your exertion, however the SystemExit is caught and swallowed, leaving your server hanging. This is conscionable 1 illustration of however overly wide objection dealing with tin make chaos.

Moreover, catching every part makes it hard to pinpoint the base origin of an content. You suffer invaluable discourse and the quality to grip circumstantial exceptions appropriately. This makes debugging a nightmare, forcing you to excavation done logs and conjecture astatine the origin of the job. Alternatively of gracefully dealing with errors and offering adjuvant suggestions, your exertion mightiness silently neglect, starring to pissed off customers and a broken estimation.

Knowing Ruby’s Objection Hierarchy

Ruby’s objection hierarchy is designed to let for granular mistake dealing with. StandardError is the basal people for about communal exceptions, similar ArgumentError, TypeError, and NoMethodError. By rescuing circumstantial exceptions, you tin tailor your consequence to the peculiar job, offering much adjuvant mistake messages and taking due act.

For illustration, if you anticipate a person to enter a figure, rescuing ArgumentError permits you to grip instances wherever non-numeric enter is supplied. You tin past immediate a broad mistake communication to the person and punctual them for legitimate enter. This focused attack leads to a much sturdy and person-affable exertion.

Champion Practices for Objection Dealing with

Truthful, what’s the correct manner to grip exceptions successful Ruby? The cardinal is to beryllium circumstantial. Rescue lone the exceptions you expect and cognize however to grip. This focused attack permits you to supply tailor-made responses and keep power complete your exertion’s behaviour.

  1. Rescue Circumstantial Exceptions: Alternatively of rescue Objection, usage rescue ArgumentError, rescue TypeError, and many others.
  2. Usage rescue => e for Elaborate Accusation: This captures the objection entity, permitting you to entree its communication and backtrace for logging and debugging.
  3. Instrumentality Retry Logic: For impermanent errors, see implementing retry logic with exponential backoff.

By pursuing these pointers, you tin make much sturdy and maintainable Ruby purposes. See besides utilizing a devoted mistake monitoring work to combination and analyse exceptions, offering invaluable insights into your exertion’s wellness.

Existent-Planet Illustration: Dealing with Record I/O Errors

Ideate you’re penning a book to procedure information from a record. Rescuing Objection might disguise captious errors similar Errno::ENOENT (record not recovered). A amended attack is to rescue StandardError and grip Errno::ENOENT particularly:

statesman record = Record.unfastened("information.txt", "r") ... procedure record ... rescue Errno::ENOENT places "Record not recovered: information.txt" rescue StandardError => e places "An mistake occurred: {e.communication}" guarantee record.adjacent if record extremity 

This focused attack permits you to supply circumstantial mistake messages and grip record not recovered errors gracefully.

Placeholder for Infographic: Visualizing Ruby’s Objection Hierarchy

  • Debar rescuing Objection until perfectly essential.
  • Grip circumstantial exceptions to better codification readability and maintainability.

Often Requested Questions

Q: What astir rescuing StandardError?

A: Rescuing StandardError is mostly a bully pattern arsenic it covers about communal exceptions with out catching scheme-flat interruptions. Nevertheless, it’s inactive important to grip circumstantial exceptions inside the StandardError artifact once imaginable to supply much focused responses.

  • Prioritize person education by offering adjuvant mistake messages.
  • Log exceptions totally for effectual debugging.

Effectual objection dealing with is important for gathering strong and dependable Ruby functions. By shifting distant from the drawback-each attack of rescue Objection and embracing much circumstantial mistake dealing with strategies, you tin importantly better the stableness, maintainability, and person education of your initiatives. Commencement refining your mistake dealing with present and reap the advantages of a much resilient codebase. Larn much astir mistake dealing with champion practices astatine Ruby Documentation. Research precocious methods similar customized objection lessons and the Rollbar mistake monitoring implement. Privation to dive deeper into circumstantial Ruby exceptions? Cheque retired this adjuvant usher connected communal Ruby exceptions.

Question & Answer :
Ryan Davis’s Ruby QuickRef says (with out mentation):

Don’t rescue Objection. Always. oregon I volition stab you.

Wherefore not? What’s the correct happening to bash?

TL;DR: Usage StandardError alternatively for broad objection catching. Once the first objection is re-raised (e.g. once rescuing to log the objection lone), rescuing Objection is most likely fine.


Objection is the base of Ruby’s objection hierarchy, truthful once you rescue Objection you rescue from every little thing, together with subclasses specified arsenic SyntaxError, LoadError, and Interrupt.

Rescuing Interrupt prevents the person from utilizing CTRLC to exit the programme.

Rescuing SignalException prevents the programme from responding appropriately to indicators. It volition beryllium unkillable but by termination -9.

Rescuing SyntaxError means that evals that neglect volition bash truthful silently.

Each of these tin beryllium proven by moving this programme, and attempting to CTRLC oregon termination it:

loop bash statesman slumber 1 eval "djsakru3924r9eiuorwju3498 += 5u84fior8u8t4ruyf8ihiure" rescue Objection places "I garbage to neglect oregon beryllium stopped!" extremity extremity 

Rescuing from Objection isn’t equal the default. Doing

statesman # iceberg! rescue # lifeboats extremity 

does not rescue from Objection, it rescues from StandardError. You ought to mostly specify thing much circumstantial than the default StandardError, however rescuing from Objection broadens the range instead than narrowing it, and tin person catastrophic outcomes and brand bug-searching highly hard.


If you person a occupation wherever you bash privation to rescue from StandardError and you demand a adaptable with the objection, you tin usage this signifier:

statesman # iceberg! rescue => e # lifeboats extremity 

which is equal to:

statesman # iceberg! rescue StandardError => e # lifeboats extremity 

1 of the fewer communal instances wherever it’s sane to rescue from Objection is for logging/reporting functions, successful which lawsuit you ought to instantly re-rise the objection:

statesman # iceberg? rescue Objection => e # bash any logging rise # not adequate lifeboats ;) extremity 

🏷️ Tags: