[Ruby] Exception handling basics


This time I studied about exceptions again I will write it so as not to forget it. This time I will try to understand little by little, so the first time: ok_woman:

What is exception handling?

This is the process to be performed when an error occurs during code execution. There are advantages such as easier investigation of the cause.

Main function to use

-** begin ** Search for processing problems by specifying the code that will cause the exception.

-** rescue ** Describe the content to be dealt with when a problem occurs.

-** raise ** Describe when you want to intentionally generate an error.

-** ensure ** Execute with or without an error.

Write something simple

The numbers are numbered with "puts" to make the flow easier to understand.

puts 1
begin           #Enclose the place where an error is likely to occur with begin
  number = 0
  answer = 100 / number
  puts 2       #↓ If an error occurs, describe the corresponding content in rescue
rescue ZeroDivisionError => e    #An object representing the exception that occurred in the e variable is assigned
  p e           #=> <ZeroDivisionError: divided by 0> 
ensure          #Execute even if an error occurs
  puts 3
puts 4

#The movement is 1 → 3 → 4

(The variable does not have to be "e".)

If an exception occurs, the process immediately after that is not performed and the rescue process is skipped.

** Exception handler ** The part of the rescue block corresponding to the exception

The output of rescue is also as follows. (Similarly described in " p e ")

Description Output contents
p "Cannot be divided by 0"(Describe the content you want to output) "Cannot be divided by 0"
p e.class ZeroDivisionError
p e.class.superclass StandardError
p e.message "divided by 0"
p e.backtrace ["exception.rb:23:in /'", "exception.rb:23:in
STDERR.puts "It's 0! !!" "It's 0! !!"(Output to standard output error)

If you write it like this, you can see various information.

Let's see how exception handling works

Allows the caller to catch the exception.

def test_exception(number)
  puts 2
    puts 3
    answer = 100 / number      #An exception occurs here! !!
    return answer
    puts 4
  rescue ZeroDivisionError => e
    puts 5
    raise e
  puts 6

puts 1

    answer = test_exception(0)
    puts 7
  rescue ZeroDivisionError => e
    puts 8
    p e               #Last executed

#The movement is 1 → 2 → 3 → 5 → 8 →#<ZeroDivisionError: divided by 0>

The exception that occurs is automatically propagated to the caller. (Returned)

You can use raise inside the rescue block to raise it intentionally and return it to the caller who raised it.

Exception handling inheritance relationship

There are many exception classes.


More details can be found here. Exception Class Reference (https://docs.ruby-lang.org/ja/latest/library/_builtin.html)

Reference: Junichi Ito. Introduction to Ruby for professionals From language specifications to test-driven development and debugging techniques


There are some things to be careful of when writing the rescue part.

    number = 0
    answer = 100 / number
rescue Exception => e
    puts "An unexpected error has occurred"
    p e
rescue ZeroDivisionError => e
    puts "It's 0! !!"
    p e

#=>An unexpected error has occurred
#=> #<ZeroDivisionError: divided by 0>

Since Exception is all superclass (parent class), the second rescue is not executed, the error is caught first, and the error text of the first Exception is output.

... so when you want to output the text you want

: zap: ** Pay attention to the order of rescue! !! **: zap:


This time, I learned like this.

Next time I would like to dig a little deeper.

Recommended Posts

[Ruby] Exception handling basics
ruby exception handling
Ruby exception handling
About Ruby exception handling
Ruby basics
Ruby basics
[Ruby] Exception handling in functions
Exception handling
Ruby basics
Exception handling Exception
Java exception handling?
About exception handling
Basics of Ruby
[Java] Exception handling
☾ Java / Exception handling
Java exception handling
Java exception handling
[Ruby] Exception handling, give back if given
Spring Boot exception handling
Ruby on Rails basics
Ruby Learning # 28 Handling Errors
Classes that require exception handling
Java's first exception handling (memories)
[Java] Practice of exception handling [Exception]
[Java] About try-catch exception handling
Java exception handling usage rules
Exception handling techniques in Java
Basics of sending Gmail in Ruby
[In-house study session] Java exception handling (2017/04/26)
[Ruby basics] split method and to_s method
[Ruby] Date, Time, Datetime class basics
[Rails] How to write exception handling?
Basics of Ruby ~ Review of confusing parts ~
Exception handling with a fluid interface
Solving with Ruby AtCoder 1st Algorithm Practical Test A Exception Handling
Step-by-step understanding of Java exception handling
[For Java beginners] About exception handling
Ruby Basics 2 ~ Review of confusing parts ~
[Ruby basics] Methods that frequently use blocks
[Ruby] From the basics to the inject method
[CoreBluetooth] Basics for handling BLE on iOS
Java (exception handling, threading, collection, file IO)
Tips for gRPC error handling in Ruby
try-catch-finally exception handling How to use java