Java 如果不使用finally,即使抛出异常,我们如何执行任何语句?
如果不使用finally,即使抛出异常,我们如何执行任何强制语句?? 此外,所使用的变量或方法仅在try块内具有作用域。这个问题是我在一次采访中提出的。请给出答案Java 如果不使用finally,即使抛出异常,我们如何执行任何语句?,java,exception-handling,Java,Exception Handling,如果不使用finally,即使抛出异常,我们如何执行任何强制语句?? 此外,所使用的变量或方法仅在try块内具有作用域。这个问题是我在一次采访中提出的。请给出答案 try{ //........ statement 1 // ....... statement 2 might throw an Exception // ....... statement 3 - A compulsory statement ne
try{
//........ statement 1
// ....... statement 2 might throw an Exception
// ....... statement 3 - A compulsory statement
needs to be executed even if exception is thrown.
}
catch {
}
这实际上只是学术性的——如果您希望在抛出异常后执行语句,那么您真的应该使用finally。但是,您可以在try-catch块中捕获异常,将语句放入catch子句中,然后重新抛出异常。强调可以,当然你不应该
/*
* DO NOT DO THIS! (Even if you could.)
*/
try {
//........ statement 1
Exception e = null;
try {
// ....... statement 2 might throw an Exception
} catch (Exception e2) {
e = e2;
}
// ....... statement 3 - A compulsory statement
// needs to be executed even if exception is thrown.
if (e!=null) {
throw e;
}
}
catch {
}
您可以将有问题的部分包装到另一个catch块中,并手动管理最终将执行的操作
try{
//........ statement 1
Exception saved = null;
try {
// ....... statement 2 might throw an Exception
} catch (Exception e) {
saved = e;
}
// ....... statement 3 - A compulsory statement
// needs to be executed even if exception is thrown.
if (saved != null) throw saved;
}
catch {
}
不过这有点问题,因为你必须
catch(Throwable)
才能最终获得与相同的效果,而且Throwable
是一个选中的异常,这意味着你必须突然声明它或使用肮脏的技巧:非常糟糕的示例永远不会这样做最后使用。JAVA开发人员已经做了很多工作来为您提供最终的解决方案
试一试{
}
抓住{
}
这就是我的建议 这个呢:
boolean flag = true;
int firstExecution = 0;
while(flag){
try{
firstExecution++;
if(firstExecution==1){
//........ statement 1
// ....... statement 2 might throw an Exception
}
// ....... statement 3 - A compulsory statement
needs to be executed even if exception is thrown.
flag=false;
}
catch {}
}
如果你想一次又一次地执行语句2,那么你可以将语句2下面的括号移到上面。对我来说,这听起来是一个奇怪的问题——这会让我在想加入相关公司时三思而后行。(这正是最终的目的……)抛出异常后,无需执行任何操作。这就是为什么终于出现了。不要在那里工作;)不,不是独家的。如果在本地catch之后写行,而本地catch不会直接将异常向上传播到调用方,那么catch块之后的每一行都会被执行。是否将语句3也放在catch中?现在你会说它的作用域只在try中吗?如果你把除了强制语句以外的所有内容都放在一个内部try-catch中呢?我也回答了同样的问题。但是他对我的回答不满意,因为在尝试{}block之后,变量会失去作用域(根据我的采访者的说法),那么他的意思是这三种说法都在同一范围内吗?不错,但有点过于复杂,是的,这有点复杂,但若用户想要一次又一次地执行语句2,那个么这将是一个简单的选项:)
boolean flag = true;
int firstExecution = 0;
while(flag){
try{
firstExecution++;
if(firstExecution==1){
//........ statement 1
// ....... statement 2 might throw an Exception
}
// ....... statement 3 - A compulsory statement
needs to be executed even if exception is thrown.
flag=false;
}
catch {}
}