Skip to content

Commit ac5bde5

Browse files
Merge pull request #11817 from rjolly/try
Add try method in safe throws strawman
2 parents d4f1c26 + 8dd1c6a commit ac5bde5

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

tests/run/safeThrowsStrawman2.check

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
1
2+
failed
3+
failed

tests/run/safeThrowsStrawman2.scala

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import language.experimental.erasedDefinitions
2+
3+
object scalax:
4+
erased class CanThrow[-E <: Exception]
5+
6+
infix type throws[R, +E <: Exception] = CanThrow[E] ?=> R
7+
8+
class Fail extends Exception
9+
10+
def raise[E <: Exception](e: E): Nothing throws E = throw e
11+
12+
private class Result[T]:
13+
var value: T = scala.compiletime.uninitialized
14+
15+
def try1[R, E <: Exception](body: => R throws E): (E => Unit) => R = { c =>
16+
val res = new Result[R]
17+
try
18+
given CanThrow[E] = ???
19+
res.value = body
20+
catch c.asInstanceOf[Throwable => Unit]
21+
res.value
22+
}
23+
24+
extension [R, E <: Exception](t: (E => Unit) => R) def catch1(c: E => Unit) = t(c)
25+
26+
import scalax._
27+
28+
def foo(x: Boolean): Int throws Fail =
29+
if x then 1 else raise(Fail())
30+
31+
def bar(x: Boolean)(using CanThrow[Fail]): Int = foo(x)
32+
def baz: Int throws Exception = foo(false)
33+
34+
@main def Test =
35+
try1 {
36+
println(foo(true))
37+
println(foo(false))
38+
} catch1 {
39+
case ex: Fail =>
40+
println("failed")
41+
}
42+
try1 {
43+
println(baz)
44+
} catch1 {
45+
case ex: Fail =>
46+
println("failed")
47+
}

0 commit comments

Comments
 (0)