7
6

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/RaiseArgs

Posted at

RuboCop | Style/RaiseArgs

概要

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

raise使用時に、下記のうちのどちらを使用しているかチェックする。

raise Exception.new(msg)
raise Exception, msg

デフォルトは後者。

設定値一覧

設定対象 対象 内容 デフォルト
RaiseArgs compact raise Exception.new(msg)形式を有効とする --
RaiseArgs exploded raise Exception, msg形式を有効とする

RaiseArgs

各設定値での検証結果をまとめます。

検証プログラム

raise_args
def fail_method
  fail StandardError, 'fail'
end

def raise_method_exploded
  fail_method
rescue
  raise StandardError, 'raise'
end

def raise_method_compact
  fail_method
rescue
  raise StandardError.new('raise')
end

begin
  raise_method_exploded
rescue => e
  puts e
end

begin
  raise_method_compact
rescue => e
  puts e
end

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

.rubocop.yml
RaiseArgs:
  EnforcedStyle: exploded
$rubocop raise_args.rb
Inspecting 1 file
C

Offenses:

raise_args.rb:14:3: C: Provide an exception class and message as arguments to raise.
  raise StandardError.new('raise')
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

1 file inspected, 1 offense detected

実行結果 compact を設定にします

.rubocop.yml
RaiseArgs:
  EnforcedStyle: compact
$rubocop raise_args.rb
Inspecting 1 file
C

Offenses:

raise_args.rb:2:3: C: Provide an exception object as an argument to fail.
  fail StandardError, 'fail'
  ^^^^^^^^^^^^^^^^^^^^^^^^^^
raise_args.rb:8:3: C: Provide an exception object as an argument to raise.
  raise StandardError, 'raise'
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

1 file inspected, 2 offenses detected

RuboCopまとめ記事

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?