Project

General

Profile

Actions

Feature #21359

open

Introduce `Exception#cause=` for Post-Initialization Assignment

Added by ioquatix (Samuel Williams) 3 days ago. Updated 2 days ago.

Status:
Open
Target version:
-
[ruby-core:122228]

Description

Ruby currently allows an exception’s cause to be explicitly set only at the time of raising using raise ..., cause: .... However, there are valid use cases where it would be convenient to set the cause when creating an exception.

The Problem

Ruby supports exception chaining via the cause: keyword during a raise, like so:

raise StandardError.new("failure"), cause: original_exception

Proposed Solution

Introduce Exception#cause= as a public setter method on Exception, allowing post-initialization assignment of the cause:

cause = RuntimeError.new("low-level error")
error = StandardError.new("higher-level error")
error.cause = cause

It would be semantically equivalent to the following implementation:

error = StandardError.new("error")
cause = RuntimeError.new("cause")

class Exception
  def cause= value
    backtrace = self.backtrace_locations

    raise self, cause: value
  rescue Exception
    self.set_backtrace(backtrace)
  end
end

p error.cause # nil
error.cause = cause
p error.cause # => #<RuntimeError: cause>

Benefits

  • Simplifies creation of rich exception objects in frameworks, tools, and tests.
  • Enables structured error chaining in asynchronous and deferred execution environments.
  • Avoids misuse of raise/rescue for control flow and metadata setting.

Related issues 1 (1 open0 closed)

Related to Ruby - Bug #21360: Inconsistent Support for `Exception#cause` in `Fiber#raise` and `Thread#raise`OpenActions
Actions

Also available in: Atom PDF

Like1
Like0Like0Like0Like0Like0Like0