Skip to content

Conversation

@liufengyun
Copy link
Contributor

@liufengyun liufengyun commented Aug 14, 2019

This implements inline rescue like those in Ruby [1], but more powerful
in that users can specify the exception to be handled.

The rescue method will be very convenient in scripting.

9 / 0 rescue 1
9 / 0 rescue { case ex: ArithmeticException => 5  }

9 / 0 rescue {
    case ex: NullPointerException => 4
    case ex: ArithmeticException => 3
}

[1] https://stackoverflow.com/questions/15396791/ruby-oneline-rescue
[2] https://bugs.ruby-lang.org/issues/6739

This implements inline `rescue` like those in Ruby [1], but more powerful
in that users can specify the exception to be handled.

The `rescue` method will be very convenient in scripting.

[1] https://stackoverflow.com/questions/15396791/ruby-oneline-rescue
Without the change, exceptions other than the following will not be propagated.
Instead, users will get `scala.MatchError`.

     op rescue {
        case ex: NullPointerException => 4
        case ex: ArithmeticException => 3
      }
However, with explict cases, user may match fatal errors except for
non-local returns, which users should not catch.
// case ex: ReturnThrowable[_] => throw ex // bug #7041
case ex: E =>
// user should never match `ReturnThrowable`, which breaks semantics of non-local return
if (fallback.isDefinedAt(ex) && !ex.isInstanceOf[ReturnThrowable[_]]) fallback(ex) else throw ex
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe E should b a subtype of Exception to avoid catching other Throwables like ReturnThrowable.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is open to discussion --- this is the case where users specify handled exceptions explicitly, but indeed ReturnThrowable should never be handled by user programs.

@nicolasstucki nicolasstucki merged commit 051f6a6 into scala:master Aug 27, 2019
@nicolasstucki nicolasstucki deleted the add-rescue branch August 27, 2019 13:53
@WojciechMazur WojciechMazur modified the milestone: 3.7.0 Mar 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants