need for "finally" clause
I can't understand the need of finally clause in java.
for eg:
try
{
System.out.println("Try");
float aQuotient = 5 / 0; // (or) float aQuotient = 5 / 2;
}
catch (Exception obj)
{
System.out.println("Catch");
}
finally
{
System.out.println("Finally");
}
can be written as
try
{
System.out.println("Try");
float aQuotient = 5 / 0; // (or) float aQuotient = 5 / 2;
}
catch (Exception obj)
{
System.out.println("Catch");
}
System.out.println("Finally");
both will give the same result. Then whats the exact need for "finally". Plz help me in this.
Thanks
Raji
[733 byte] By [
raji_gobia] at [2007-11-27 1:31:24]

> I can't understand the need of finally clause in
> java.
The difference between the two pieces of code you wrote is that the code in the "finally" clause is guaranteed to execute, while the code outside of that is not.
(did anyone otehr'n me wince when they saw the subject line here?)
> Write this without finally:
> > void m() throws IOException {
>try {
>InputStream in = new FileInputStream(...);
>//use in
>...
> } finally {
> in.close();
>
>
Quick question:
Variables defined in a try block only exist for the scope of the try..catch block, correct? Therefore, in the quoted code, wouldn't that code not compile? I remember having some issue like that, but I forgot what happened.
D'oh! You are right. I should have written:
void m() throws IOException {
InputStream in = new FileInputStream(...);
try {
...
//use in
...
} finally {
in.close();
}
}
... which is a common template.