Skip to content

Commit b364d38

Browse files
committed
Add What To Do When You Don't Rescue as a ruby til
1 parent f6c495a commit b364d38

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
1010
For 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)
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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)

0 commit comments

Comments
 (0)