nekoinemo
03/30/2017, 2:31 PMinfix fun <T : RuntimeException> (() -> Unit).shouldThrow(type: Class<T>) {
try {
this()
} catch (e: T) {
return
} catch (e: Exception) {
throw IllegalStateException("Thrown unexpected exception ${e::class.java.canonicalName}")
}
throw IllegalStateException("Didn't throw exception")
}
class GLException : java.lang.RuntimeException()
fun main(args: Array<String>) {
try {
{ throw GLException() } shouldThrow (GLException::class.java)
println("reached here")
} catch (e: Exception) {
e.printStackTrace()
}
try {
{ throw IllegalAccessException() } shouldThrow (GLException::class.java)
println("didn't reach here")
} catch (e: Exception) {
e.printStackTrace()
}
}
If somebody can point out exactly why it works perfectly even though @miha-x64 says it shouldn't - i would be grateful.