java 我可以在一个班级中有两个以上的 finally 块吗
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13306922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
can I have more than two finally block in a class
提问by arvin_codeHunk
I am working on a project where I need to perform two different operation. I have a finally block in my main controller method.
我正在做一个需要执行两种不同操作的项目。我的主控制器方法中有一个 finally 块。
My question is, can I have more than two finally, for example:
我的问题是,我最后能不能有两个以上,例如:
class test
{
X()
{
try
{
//some operations
}
finally
{
// some essential operation
}
}
//another method
Y()
{
try
{
//some operations
}
finally
{
// some another essential operation
}
}
}
so,is it possible?
那么,有可能吗?
回答by Jon Skeet
You can only have one finally
clause per try/catch/finally statement, but you can have multiple such statements, either in the same method or in multiple methods.
每个 try/catch/finally 语句只能有一个finally
子句,但可以有多个这样的语句,在同一个方法中或在多个方法中。
Basically, a try/catch/finally statement is:
基本上,一个 try/catch/finally 语句是:
try
catch
(0 or more)finally
(0 or 1)
try
catch
(0个或更多)finally
(0 或 1)
... but there must be at leastone of catch
/finally
(you can't have just a "bare" try
statement)
...但必须至少有一个catch
/ finally
(你不能只有一个“裸”try
语句)
Additionally, you can nest them;
此外,您可以嵌套它们;
// Acquire resource 1
try {
// Stuff using resource 1
// Acquire resource 2
try {
// Stuff using resources 1 and 2
} finally {
// Release resource 2
}
} finally {
// Release resource 1
}
回答by Azodious
can I have more than two finally
最后我能有两个以上吗
Yes, you can have as many try - catch - finally
combination you want but they all should be correctly formatted. (i.e syntax should be correct)
是的,您可以拥有任意数量的try - catch - finally
组合,但它们都应该正确格式化。(即语法应该是正确的)
In your example, you've written correct syntax and it'll work as expected.
在您的示例中,您编写了正确的语法,它会按预期工作。
You can have in following way:
您可以通过以下方式获得:
try
{
}
catch() // could be more than one
{
}
finally
{
}
OR
或者
try
{
try
{
}
catch() // more than one catch blocks allowed
{
}
finally // allowed here too.
{
}
}
catch()
{
}
finally
{
}
回答by Surya
public class Example {
public static void main(String[] args) {
try{
try{
int[] a =new int[5];
a[5]=4;
}catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Out Of Range");
}finally{
System.out.println("Finally Outof Range Block");
}
try{
int x=20/0;
}catch (ArithmeticException e)
{
System.out.println("/by Zero");
}finally{
System.out.println("FINALLY IN DIVIDES BY ZERO");
}
}catch (Exception e) {
System.out.println("Exception");
}
finally{
System.out.println("FINALLY IN EXCEPTION BLOCK");
}
System.out.println("COMPLETED");
}
}
......
......