首页 > 解决方案 > Why try block only is not allowed?

问题描述

Why in Kotlin (also in Java except the case of try-with-resources) it is not possiable to write a try{} block only ? for example:

this function is allowed

fun tryFunction(){
    try{print("hello world!")}finally {}
}

while this one is not allowed

fun tryFunction(){
    try{print("hello world!")} //build error "Expecting 'catch' or 'finally'"
}

in spite of finally{} block at the first example does nothing

标签: javakotlintry-catch

解决方案


“try/catch”、“try/catch/finally”和“try/finally”是什么意思

  • “尝试做某事,如果失败了……”
  • “尝试做某事,如果失败就做……然后做……”
  • “尝试做某事,然后做......”分别。

Try 本身只是意味着“尝试做某事”——它隐含在所有你想要尝试做的代码中;所以你不需要像 a 这样的多余的东西try来表达它。

如果您只是想将语句放在它们自己的块中,例如将变量范围限定到该块,您总是可以省略try.

关于你为什么finally允许一个空块的问题:它只是finally应该跟着一个块,并且一个块没有语句是有效的。非常罕见的是,您应该拥有一个空的 finally 块,因此不值得将其设为特殊的“非空块”语法元素。


推荐阅读