1
3

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 5 years have passed since last update.

try except について

Posted at

今回は私がHackerRankの30 Days of Code をやっていたときに出てきた問題について書きたいと思います。

try except

問題の内容はインプットされたものが整数ならばそのまま出力し、文字列がインプットされればBad Stringと出力する。

qiita.rb
s = input()
try:
   print(int(s))
except ValueError: 
   print("Bad String")

コードはこのようなシンプルなものになりました。
このコードの解説をすると、インプットで受け取ったものをtryでintに変換しようと試みる。もしそれが数字ならばもちろん変換することができるが、文字列であるとエラーとなってしまいます。exceptの後にそのエラー文を書いて、「このエラー文が出た時はこのような対処を行うと」と設定します。このようにtry exceptを使うことによってこの類の問題を解決することができます。

1
3
0

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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?