proper try/catch/finally

This commit is contained in:
Alex Tkachman
2011-11-16 14:26:16 +02:00
parent 3b17b3fac7
commit 1b04870fa4
7 changed files with 188 additions and 28 deletions
@@ -0,0 +1,52 @@
fun test1() : Boolean {
try {
return true
} finally {
if(true) // otherwise we wisely have unreachable code
return false
}
}
var x = true
fun test2() : Boolean {
try {
} finally {
x = false;
}
return x
}
fun test3() : Int {
var y = 0
try {
++y
} finally {
++y
}
return y
}
var z = 0
fun test4() : Int {
z = 0
return try {
try {
z++
}
finally {
z++
}
} finally {
++z
}
}
fun box() : String {
if(test1()) return "test1 failed"
if(test2()) return "test2 failed"
if(test3() != 2) return "test3 failed"
System.out?.println(test4())
if(test4() != 3) return "test4 failed"
return "OK"
}
@@ -0,0 +1,30 @@
var GUEST_USER_ID = 3
val USER_ID =
try {
getUserIdFromEnvironment()
}
catch (e : UnsupportedOperationException) {
++GUEST_USER_ID
}
val USER_ID_2 =
try {
getUserIdFromEnvironment()
}
catch (e : UnsupportedOperationException) {
GUEST_USER_ID
}
finally {
GUEST_USER_ID++
}
fun getUserIdFromEnvironment() : Int = throw UnsupportedOperationException()
fun box() : String {
System.out?.println("G: " + GUEST_USER_ID + " U1:" + USER_ID + " U2: " + USER_ID_2)
if(USER_ID != 4) return "test0 failed"
if(USER_ID_2 != 4) return "test2 failed"
if(GUEST_USER_ID != 5) return "test3 failed"
return "OK"
}
@@ -0,0 +1,24 @@
class Reluctant() {
{
throw Exception("I'm not coming out")
}
}
fun p(o : Any?) = System.out?.println(o)
fun test1() : String {
try {
val b = Reluctant()
return "Surprise!"
}
catch (ex : Exception) {
return "I told you so"
}
}
fun box() : String {
if(test1() != "I told you so") return "test1 failed"
return "OK"
}