LoginSignup
0
0

More than 1 year has passed since last update.

数値を0で割った時にZeroDivisionErrorが返ってこない件

Last updated at Posted at 2023-04-23

初めに例外処理の使い方

基本

begin
  # エラーを発生させる可能性のあるコード。
rescue
  # エラー発生時の処理。
end

begin
  p num1 / num2
rescue => e 
  p e.message #=> error
end

エラーを変数eに格納しmessageメソッドでエラー内容を表示。

詰まったこと

割り算の際に0で割ると、ZeroDivisionErrorが返ってきて
「0による割り算は許可されていません」と出力させたい。
num1,num2をgets.chomp.to_iとするとZeroDivisionErrorがしっかり返ってきてくる。

puts '1番目の整数を入力してください:'
num1 = gets.chomp.to_f
puts '2番目の整数を入力してください:'
num2 = gets.chomp.to_f

begin
  p num1 / num2
rescue ZeroDivisionError => e
  p e.message
  p '0による割り算は許可されていません'
rescue => e
  p e.message
end

解決方法

raise ZeroDivisionError if num2.zero?

num2に0が入力されたときはZeroDivisionErrorを返すコードを書く

原因

浮動小数点(Float型)/0をしたときはInfinityが返ってくる仕様だった。
https://docs.ruby-lang.org/ja/latest/method/Float/i/=2f.html

最後に

原因は簡単なことだった。
しかし他の箇所のコードが間違っているのではないのかと思って調べており、時間を要した。
まずは公式ドキュメントを読むように心がける。

0
0
2

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