Skip to content

Commit e31e80d

Browse files
author
Bozhidar Batsov
committed
expanded the section on exceptions
1 parent a48666f commit e31e80d

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

README.md

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -796,9 +796,90 @@ in *Ruby* now, not in *Python*.
796796
## Exceptions
797797

798798
* Don't suppress exceptions.
799+
800+
```Ruby
801+
begin
802+
# an exception occurs here
803+
rescue SomeError
804+
# the rescue clause does absolutely nothing
805+
end
806+
```
807+
799808
* Don't use exceptions for flow of control.
809+
810+
```Ruby
811+
# bad
812+
begin
813+
n / d
814+
rescue ZeroDivisionError
815+
puts "Cannot divide by 0!"
816+
end
817+
818+
# good
819+
if n.zero?
820+
puts "Cannot divide by 0!"
821+
else
822+
n / d
823+
```
824+
800825
* Avoid rescuing the `Exception` class.
801826

827+
```Ruby
828+
# bad
829+
begin
830+
# an exception occurs here
831+
rescue
832+
# exception handling
833+
end
834+
835+
# still bad
836+
begin
837+
# an exception occurs here
838+
rescue Exception
839+
# exception handling
840+
end
841+
```
842+
843+
* Put more specific exceptions higher up the rescue chain, otherwise
844+
they'll never be rescued from.
845+
846+
```Ruby
847+
# bad
848+
begin
849+
# some code
850+
rescue Exception => e
851+
# some handling
852+
rescue StandardError => e
853+
# some handling
854+
end
855+
856+
# good
857+
begin
858+
# some code
859+
rescue StandardError => e
860+
# some handling
861+
rescue Exception => e
862+
# some handling
863+
end
864+
```
865+
866+
* Release external resources obtained by your program in an ensure
867+
block.
868+
869+
```Ruby
870+
f = File.open("testfile")
871+
begin
872+
# .. process
873+
rescue
874+
# .. handle error
875+
ensure
876+
f.close unless f.nil?
877+
end
878+
```
879+
880+
* Favor the use of exceptions for the standard library over
881+
introducing new exception classes.
882+
802883
## Collections
803884
804885
* Prefer `%w` to the literal array syntax when you need an array of

0 commit comments

Comments
 (0)