[英]Jumping from a try block to a finally block
我正在嘗試執行以下操作:
String txt = "begin\n";
try{
// some stuff
if(some condition)
JUMP TO FINALLY CODE
// some other stuff
} finally {
String txt += "end\n";
return txt;
}
有沒有一種方法可以在不引發異常的情況下實現JUMP TO FINALLY CODE
(在我看來,引發異常看起來並不干凈)
是的,一種方法是從這樣的方法中return
String txt = "begin\n";
try{
// some stuff
if(some condition)
return;
// some other stuff
} finally {
String txt += "end\n";
}
不需要任何方法跳轉到finally
因為這里總是finally
塊執行。 是否存在Exception
。
如果您不想執行下面的代碼行,則可以使用return
try {
if(isThisShouldReturn()){
return; // when if satisfied will return from try
} else {
// do the stuff
}
}finally {
System.out.println("come to finally");
}
我的方法是消除條件:
String txt = "begin\n";
try{
// some stuff
if(!someCondition) {
// some other stuff
}
} finally {
String txt += "end\n";
}
這將具有您的示例的預期行為。
我猜return和通過拋出異常是您可以從try塊中到達finally塊的僅有兩種方法。
您需要結合使用標簽和中斷; 就像是:
end_try: try {
...
break end_try;
...
} finally {
...
}
要么:
try {
...
end_try: {
break end_try;
}
} finally {
...
}
//從try塊或引發異常。//使用return調用:
try
{
if(true condition)
{
return;
}
else
{
//false condition do work....
}
}
finally
{
//always executed.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.