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?
No you can't
you can use Try-catch-finally
or try-finally
try {
}catch (Exception e){
}
finally{
}
or
try {
}
finally{
}
finally
should have atleast a try
block, catch
is optional. The point of finally blocks is to make sure stuff gets cleaned up whether an exception is thrown or not. As per the JLS
A finally clause ensures that the finally block is executed after the try block and any catch block that might be executed, no matter how control leaves the try block or catch block.
Hence a finally
should always be preceded by a try
block.
The finally block always executes when the try block exits. So you can use finally without catch but you must use try.
For more details check doc here
If an exception is thrown prior to the try block, the finally code will not execute. The finally block always executes when the try block exits. So you can use finally without catch but you must use try.