Issue #10481 has been updated by Alex Boyd.


Nobuyoshi Nakada wrote:
> With your patch, the condition is checked *after* matching against the exception classes, not a part of the matching, right?
> Which behavior is preferred?

They're checked after checking for a match against the exception classes, so the conditions won't be run at all if the exception class doesn't match, but they'll cause the next `rescue` clause to be checked if they fail instead of skipping all remaining `rescue` clauses like `raise unless some_condition` would. Is that what you're asking?

(If so, I, for one, prefer this behavior.)

----------------------------------------
Feature #10481: Add "if" and "unless" clauses to rescue statements
https://bugs.ruby-lang.org/issues/10481#change-50038

* Author: Alex Boyd
* Status: Open
* Priority: Normal
* Assignee: Yukihiro Matsumoto
* Category: 
* Target version: 
----------------------------------------
I'd like to propose a syntax change: allow boolean "if" and "unless" clauses to follow a rescue statement.

Consider the following:

~~~
begin
  ...
rescue SomeError => e
  if e.error_code == 1
    ...handle error...
  else
    raise
  end
end
~~~

This is a fairly common way of dealing with exceptions where some condition above and beyond the exception's type determines whether the exception should be rescued. It's verbose, though, and it's not obvious at first glance exactly what conditions are being rescued, especially if "...handle error..." is more than a few lines long. I propose that the following be allowed:

~~~
begin
  ...
rescue SomeError => e if e.error_code == 1
  ...handle error...
end
~~~

"unless" would, of course, be allowed as well:

~~~
begin
  ...
rescue SomeError => e unless e.error_code == 2
  ...handle error...
end
~~~

A rescue statement whose boolean condition failed would be treated the same as if the exception being raised didn't match the exception being rescued, and move on to the next rescue statement:

~~~
begin
  ...
rescue SomeError => e if e.error_code == 1
  ...handle error code 1...
rescue SomeError => e if e.error_code == 2
  ...handle error code 2...
end
~~~

And finally, catch-all rescue statements would be allowed as well:

~~~
begin
  ...
rescue => e if e.message == "some error"
  ...handle error...
end
~~~


---Files--------------------------------
rescue-conditions.diff (6.76 KB)
rescue-conditions.diff (6.57 KB)


-- 
https://bugs.ruby-lang.org/