0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Ruby 入門 [例外を処理]

Last updated at Posted at 2021-09-12

● 例外を処理する

例外処理
begin
 #例外が発生する可能性がある処理
rescue
 #例外が発生した時に実行する処置(rescue節)
end
puts "金額を入力してください"
bill = gets.to_i
puts "割り勘する人数を入力してください"
number = gets.to_i

begin
    warikan = bill / number
    puts "1人あたり#{warikan}円です"
rescue ZeroDivisionError
    # ZeroDivisionError例外が発生したらメッセージを表示する
    puts "おっと、0人では割り切れません"
end
↪️金額を入力してください
 100
 割り勘する人数を入力してください
 0
 おっと0人では割り切れません ——#例外がなければ発生しない
↪️金額を入力してください
 100
 割り勘する人数を入力してください
 4
 1人あたり25円です

例外がなければrescue節は発生しない。
0で割り算した時に発生するZeroDivisionError例外を処理する時はrescue ZeroDivisionErrorと書く。

メソッド内で例外処理を書く場合は、beginとrescueを省略できる。メソッドの初めからrescueまでの処理で発生した例外を、rescue節で受け入れる。

def warikan(bill, number)
    warikan = bill/number
    puts "1人あたり#{warikan}円です"
rescue ZeroDivisionError
    # ZeroDivisionError例外が発生したらメッセージを表示する
    puts "おっと、0人では割り勘できません"    
end

warikan(100,0)
warikan(100,1)
warikan(100,2)
↪️おっと0人では割り勘できません
 1人あたり100円です
 1人あたり50円です

Ruby2.5以降ではブロック内でもbeginとendを省略できる。

bill = 100
numbers = [0,1,2]

numbers.each do |number|
    warikan = bill/number
    puts "1人あたり#{warikan}円です"
rescue ZeroDivisionError
    puts "おっと、0人では割り勘できません"
end   
↪️おっと0人では割り勘できません
 1人あたり100円です
 1人あたり50円です
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?