Avoid using 'rescue' as a modifier

이 페이지는 아직 한국어로 제공되지 않으며 번역 작업 중입니다. 번역에 관한 질문이나 의견이 있으시면 언제든지 저희에게 연락해 주십시오.

Metadata

ID: ruby-best-practices/no-rescue-modifier

Language: Ruby

Severity: Notice

Category: Best Practices

Description

This rule emphasizes the importance of not using ‘rescue’ as a modifier in your code. Using ‘rescue’ as a modifier can lead to confusion and potential bugs in the code. This is because it can catch exceptions you did not intend to catch and miss the ones you intended to catch. Hence, it’s considered a bad practice.

The importance of this rule lies in ensuring the clarity and correctness of your error handling code. When ‘rescue’ is used as a modifier, it can catch StandardError and its subclasses by default. This can lead to unexpected behavior if you intended to catch a different exception.

Good coding practices to avoid this rule violation include explicitly stating the exception you are trying to catch, and using ‘rescue’ in a begin-end block instead of as a modifier. This makes your code easier to understand and less prone to bugs. For example, instead of writing foo = a[x] rescue nil, write:

begin
  foo = a[x]
rescue IndexError
  foo = nil
end

This way, it’s clear that you are trying to rescue IndexError, and not any other kind of error.

Non-Compliant Code Examples

foo = a[x] rescue nil

something rescue handle_error

# This is a common mistake: it doesn't capture SomeException.
# It captures StandardError and names the variable `SomeException`.
anything rescue SomeException

Compliant Code Examples

try
  foo = a[x]
rescue IndexError
  foo = nil
end

try
  something
rescue StandardError
  handle_error
end
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis

PREVIEWING: rtrieu/product-analytics-ui-changes