Skip to content

Commit 910f6b3

Browse files
committed
Use partial functions in interface (thanks @smarter)
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 }
1 parent b96a908 commit 910f6b3

File tree

1 file changed

+35
-8
lines changed

1 file changed

+35
-8
lines changed

tests/run/rescue.scala

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,45 @@
11
object lib {
2-
inline def (op: => T) rescue[T] (fallback: => T) = try op catch { case _: Throwable => fallback }
3-
inline def (op: => T) rescue[T, E <: Throwable] (fallback: E => T) = try op catch { case ex: E => fallback(ex) }
2+
inline def (op: => T) rescue[T] (fallback: => T) =
3+
try op
4+
catch {
5+
case _: Throwable => fallback
6+
}
7+
8+
inline def (op: => T) rescue[T, E <: Throwable] (fallback: PartialFunction[E, T]) =
9+
try op
10+
catch {
11+
case ex: E =>
12+
if (fallback.isDefinedAt(ex)) fallback(ex) else throw ex
13+
}
414
}
515

616
import lib._
717

818
@main def Test = {
919
assert((9 / 1 rescue 1) == 9)
1020
assert((9 / 0 rescue 1) == 1)
11-
assert(((9 / 0 rescue { ex: NullPointerException => 5 }) rescue 10) == 10)
12-
assert(((9 / 0 rescue { ex: ArithmeticException => 5 }) rescue 10) == 5)
21+
assert(((9 / 0 rescue { case ex: NullPointerException => 5 }) rescue 10) == 10)
22+
assert(((9 / 0 rescue { case ex: ArithmeticException => 5 }) rescue 10) == 5)
23+
24+
assert(
25+
{
26+
9 / 0 rescue {
27+
case ex: NullPointerException => 4
28+
case ex: ArithmeticException => 3
29+
}
30+
} == 3
31+
)
1332

14-
assert((9 / 0 rescue {
15-
case ex: NullPointerException => 4
16-
case ex: ArithmeticException => 3
17-
}) == 3)
33+
assert(
34+
{
35+
{
36+
val a = 9 / 0 rescue {
37+
case ex: NullPointerException => 4
38+
}
39+
a * a
40+
} rescue {
41+
case ex: ArithmeticException => 3
42+
}
43+
} == 3
44+
)
1845
}

0 commit comments

Comments
 (0)