can I have more than two finally block in a class
Solution 1
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)
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
{
}
Solution 2
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.
Basically, a try/catch/finally statement is:
try
catch
(0 or more)finally
(0 or 1)
... but there must be at least one of catch
/finally
(you can't have just a "bare" try
statement)
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
}
Comments
-
arvin_codeHunk about 4 years
I am working on a project where I need to perform two different operation. I have a finally block in my main controller method.
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?