File tree Expand file tree Collapse file tree 2 files changed +37
-1
lines changed Expand file tree Collapse file tree 2 files changed +37
-1
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
1010For a steady stream of TILs from a variety of rocketeers, checkout
1111[ til.hashrocket.com] ( https://til.hashrocket.com/ ) .
1212
13- _ 826 TILs and counting..._
13+ _ 827 TILs and counting..._
1414
1515---
1616
@@ -685,6 +685,7 @@ _826 TILs and counting..._
685685- [ Use A Case Statement As A Cond Statement] ( ruby/use-a-case-statement-as-a-cond-statement.md )
686686- [ Use dotenv In A Non-Rails Project] ( ruby/use-dotenv-in-a-non-rails-project.md )
687687- [ Using BCrypt To Create And Check Hashed Passwords] ( ruby/using-bcrypt-to-create-and-check-hashed-passwords.md )
688+ - [ What To Do When You Don't Rescue] ( ruby/what-to-do-when-you-dont-rescue.md )
688689- [ Who Are My Ancestors?] ( ruby/who-are-my-ancestors.md )
689690- [ Wrap Things In An Array, Even Hashes] ( ruby/wrap-things-in-an-array-even-hashes.md )
690691- [ Zero Padding] ( ruby/zero-padding.md )
Original file line number Diff line number Diff line change 1+ # What To Do When You Don't Rescue
2+
3+ Ruby's ` rescue ` syntax supports a couple different blocks. I was already
4+ familiar with ` ensure ` which is a block of code that will be executed
5+ regardless of whether or not an exception was rescued.
6+
7+ ``` ruby
8+ begin
9+ do_something_that_could_fail()
10+ rescue StandardError => e
11+ // oh no!
12+ ensure
13+ Logging .info(" We attempted to do the thing." )
14+ end
15+ ```
16+
17+ What if you want to differentiatee between an instance when your code ran
18+ without incident and when there was an exception? Ruby's ` rescue ` syntax also
19+ supports an ` else ` block. The ` else ` block is executed only when nothing is
20+ rescued.
21+
22+ ``` ruby
23+ begin
24+ do_something_that_could_fail()
25+ rescue StandardError => e
26+ Logging .info(" We tried to do something and it failed." )
27+ else
28+ Logging .info(" We successfully did the thing!" )
29+ end
30+ ```
31+
32+ There are a lot of ways to use this. Here I was able to differentiate the
33+ messaging in my logging based on whether or not an exception occurred.
34+
35+ [ source] ( https://blog.bigbinary.com/2017/10/24/ruby-2.5-allows-rescue-inside-do-end-blocks.html )
You can’t perform that action at this time.
0 commit comments