From b364d3874d704da18c7a621c298b86ca2d5e0c7f Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 19 Jul 2019 13:22:29 -0500 Subject: [PATCH] Add What To Do When You Don't Rescue as a ruby til --- README.md | 3 ++- ruby/what-to-do-when-you-dont-rescue.md | 35 +++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 ruby/what-to-do-when-you-dont-rescue.md diff --git a/README.md b/README.md index 5af4a71..4e44afb 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_826 TILs and counting..._ +_827 TILs and counting..._ --- @@ -685,6 +685,7 @@ _826 TILs and counting..._ - [Use A Case Statement As A Cond Statement](ruby/use-a-case-statement-as-a-cond-statement.md) - [Use dotenv In A Non-Rails Project](ruby/use-dotenv-in-a-non-rails-project.md) - [Using BCrypt To Create And Check Hashed Passwords](ruby/using-bcrypt-to-create-and-check-hashed-passwords.md) +- [What To Do When You Don't Rescue](ruby/what-to-do-when-you-dont-rescue.md) - [Who Are My Ancestors?](ruby/who-are-my-ancestors.md) - [Wrap Things In An Array, Even Hashes](ruby/wrap-things-in-an-array-even-hashes.md) - [Zero Padding](ruby/zero-padding.md) diff --git a/ruby/what-to-do-when-you-dont-rescue.md b/ruby/what-to-do-when-you-dont-rescue.md new file mode 100644 index 0000000..b27dc1e --- /dev/null +++ b/ruby/what-to-do-when-you-dont-rescue.md @@ -0,0 +1,35 @@ +# What To Do When You Don't Rescue + +Ruby's `rescue` syntax supports a couple different blocks. I was already +familiar with `ensure` which is a block of code that will be executed +regardless of whether or not an exception was rescued. + +```ruby +begin + do_something_that_could_fail() +rescue StandardError => e + // oh no! +ensure + Logging.info("We attempted to do the thing.") +end +``` + +What if you want to differentiatee between an instance when your code ran +without incident and when there was an exception? Ruby's `rescue` syntax also +supports an `else` block. The `else` block is executed only when nothing is +rescued. + +```ruby +begin + do_something_that_could_fail() +rescue StandardError => e + Logging.info("We tried to do something and it failed.") +else + Logging.info("We successfully did the thing!") +end +``` + +There are a lot of ways to use this. Here I was able to differentiate the +messaging in my logging based on whether or not an exception occurred. + +[source](https://blog.bigbinary.com/2017/10/24/ruby-2.5-allows-rescue-inside-do-end-blocks.html)