tca*_*cak 5 d compiler-errors exception
我正在为TCPServer编写一个方法.我编写了如下代码:
// thread run
protected void threadRun(){
// continue running. don't stop
while(true){
try{
try{
}
catch(Exception e1){
try{
} catch(Exception e2){}
finally{
// skip
continue;
}
}
}
catch(Exception e3){
}
}
}
Run Code Online (Sandbox Code Playgroud)
内容并不重要.有代码接受客户端等,但我删除它们以确保它不是关于细节.无论如何,当我尝试编译这段代码时,编译器会为该continue行说:
Error: continue is not inside a loop
通过认为我可能知道它错了,我用Java编写了完整相同的代码,如下所示:
class test{
public static void main(String[] args){
while(true){
try{
try{
}
catch(Exception e1){
try{
} catch(Exception e2){}
finally{
continue;
}
}
}
catch(Exception e3){
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
正如我所料,java编译器不会提供任何错误消息并成功编译.问题到底是什么?
显然,continue( 和break) 无法打破障碍finally。编译这个:
void run() {
loop:
while (true) {
try {}
catch (Exception e) {}
finally {
continue loop;
}
}
}
Run Code Online (Sandbox Code Playgroud)
会给你这个(省略标签会产生与你得到的相同的错误):
Error: cannot continue out of finally block
Run Code Online (Sandbox Code Playgroud)
我还没有找到这种限制的理由或解释(编辑:请参阅下面棘轮怪胎的评论)。然而,我无法想象这是一个超级常见的用例。您可能想看看其他选择。