Skip to content

Commit bf37dce

Browse files
committed
Add rescue to support streamline error handling
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
1 parent 0ebbcff commit bf37dce

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

tests/run/rescue.scala

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
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) }
4+
}
5+
6+
import lib._
7+
8+
@main def Test = {
9+
assert((9 / 1 rescue 1) == 9)
10+
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)
13+
}

0 commit comments

Comments
 (0)