I am trying to use the finally block without using the try/catch blocks but getting the error in Eclipse.
Can I use the finally block without using the try/catch blocks?
A try statement should have either catch block or finally block, it can have both blocks.
We can’t write any code between try-catch-finally block.
We can’t have catch or finally clause without a try statement.
We can have multiple catch blocks with a single try statement.try-catch blocks can be nested similar to if-else statements.
We can have only one finally block with a try-catch statement.
From Oracle Trails:
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.
From the above statement, you cannot have finally block alone on its own. below are the combinations allowed.
try catch finally
try catch
try finally
try {
// Block of code with multiple exit points
}
finally {
// Block of code that must always be executed when the try block
// is exited, no matter how the try block is exited
}
The code within the finally
block is guaranteed to execute if program control flow enters the corresponding try
block. So it makes no sense to have a finally
without a try
.
The only exception to this is if the program encounters a System.exit(...)
call before the finally
block, as that shuts down the virtual machine.
You must have a try
block with a finally
block. The try
block defines which lines of code will be followed by the finally
code. If an exception is thrown prior to the try
block, the finally
code will not execute.
Adding catch
blocks is optional:
try {
// something
} finally {
// guaranteed to run if execution enters the try block
}
The reason why you cannot have a finally
without a try
is because you could have multiple finally
statements in the same scope and the try
indicates what block of code the finally
pertains to in case an error occurs.
Another interesting feature of the finally
is that it must execute no matter what when the try
is entered. For example what if you use a goto
to skip over your finally
statement? If the goto
is inside of the try
it will execute the finally
statement however if the goto
is above/outside the try
statement then it will skip the finally
code. finally
is relevant only to the code that is surrounded in the try
. If you have no try then the finally
is not relevant to anything.