5
7

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.

RuboCop | Style/SignalException

Last updated at Posted at 2014-07-23

RuboCop | Style/SignalException

概要

RuboCopの「Style/SignalException」警告について。

例外の送出時に、 raise を利用するか、 fail を利用するかを設定し、チェックする。
デフォルトでは文脈に合わせて使い分けをしているかチェックする。
新規に例外を送出する場合は fail
例外を再送出する場合は raise

SignalException

設定値一覧

設定対象 対象 内容 デフォルト
EnforcedStyle only_raise raiseのみを許容する --
EnforcedStyle only_fail failのみを許容する --
EnforcedStyle semantic 文脈に合わせる

検証プログラム

signal_exception.rb
def hoge(msg)
  hige(msg)
rescue
  fail StandardError, 'hoge'
end

def hige(msg)
  if msg == 'hoge'
    print msg
  else
    raise StandardError, 'hige'
  end
end

実行結果 デフォルト の場合

.rubocop.yml
SignalException:
  EnforcedStyle: semantic
$ rubocop
Inspecting 1 file
C

Offenses:

signal_exception.rb:4:3: C: Use raise instead of fail to rethrow exceptions.
  fail StandardError, 'hoge'
  ^^^^
signal_exception.rb:11:5: C: Use fail instead of raise to signal exceptions.
    raise StandardError, 'hige'
    ^^^^^

1 file inspected, 2 offenses detected

実行結果 only_raise に設定します

.rubocop.yml
SignalException:
  EnforcedStyle: only_raise
$ rubocop
Inspecting 1 file
C

Offenses:

signal_exception.rb:4:3: C: Always use raise to signal exceptions.
  fail StandardError, 'hoge'
  ^^^^

1 file inspected, 1 offense detected

実行結果 only_fail に設定します

.rubocop.yml
SignalException:
  EnforcedStyle: only_fail
$ rubocop
Inspecting 1 file
C

Offenses:

signal_exception.rb:11:5: C: Always use fail to signal exceptions.
    raise StandardError, 'hige'
    ^^^^^

1 file inspected, 1 offense detected

補足

この警告は rubocop -a で修正可能です。

RuboCopまとめ記事

5
7
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
5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?