java - 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
解决方案
“try/catch”、“try/catch/finally”和“try/finally”是什么意思
- “尝试做某事,如果失败了……”
- “尝试做某事,如果失败就做……然后做……”
- “尝试做某事,然后做......”分别。
Try 本身只是意味着“尝试做某事”——它隐含在所有你想要尝试做的代码中;所以你不需要像 a 这样的多余的东西try
来表达它。
如果您只是想将语句放在它们自己的块中,例如将变量范围限定到该块,您总是可以省略try
.
关于你为什么finally
允许一个空块的问题:它只是finally
应该跟着一个块,并且一个块没有语句是有效的。非常罕见的是,您应该拥有一个空的 finally 块,因此不值得将其设为特殊的“非空块”语法元素。
推荐阅读
- angularjs - 角度ngrx效果
- android - 在 xamarin.forms 中隐藏 android 选择器上的取消按钮
- android - android通知remoteInput显示问题
- asp.net - 如果我在部署到生产环境后更改 JSON 文件中的任何内容,则更改不会反映我浏览
- asp.net - 使用 List & Label 浏览器插件或 ActiveX 控件在 ASP.NET 应用程序中进行预览
- c++ - 没有使用指针和偏移量获得正确的地址
- excel - 剪切后VBA范围变量消失
- linux - 如何从 perf stat 的输出中解析指令数和经过的时间
- javascript - 在 Reactjs 中存储和获取对象数组
- sql - 使用 SQL 样式的 INSERT 创建逐行数据框以提高易读性