finally block is optional??

M

Matt

I want to know if finally block is optional? I tested this myself, and
the following yield the same output.

void f()
{
try
{ //code1
}
catch()
{
}
finally
{ //code2
}
}

void f()
{
try
{ //code1
}
catch()
{
}
//code2
}


please advise. thanks!!
 
T

Tony Morris

Matt said:
I want to know if finally block is optional? I tested this myself, and
the following yield the same output.

void f()
{
try
{ //code1
}
catch()
{
}
finally
{ //code2
}
}

void f()
{
try
{ //code1
}
catch()
{
}
//code2
}


please advise. thanks!!

Yes it's optional.
In your example, you aren't guaranteed the same result each time.
Hence, there is a purpose to the use of a finally block.

http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html

Good luck

--
Tony Morris
(BInfTech, Cert 3 I.T.)
Software Engineer
(2003 VTR1000F)
Sun Certified Programmer for the Java 2 Platform (1.4)
Sun Certified Developer for the Java 2 Platform
 
S

Stefan Waldmann

Matt said:
I want to know if finally block is optional? I tested this myself, and
the following yield the same output.

[snip]
please advise. thanks!!

Hi,

yes, it's optional. You only need it, if you want code to be executed in
any case, even if an exception is thrown. You can even write a
try/finally without catch, for example:

public static void finallyTest() throws Exception
{
try {
throw new Exception("my very own Exception");
}
finally {
System.out.println("This is printed anyway");
}

}


Stefan


P.S.: You'd rather post your newbie questions in comp.lang.java.help, or
better, get a book where basics like this are explained, for example
"Thinking in Java" by Bruce Eckel - free to download from one of the
mirrors at:

<http://mindview.net/Books/TIJ/DownloadSites>

Thanks!
 
G

Guest

Matt said:
I want to know if finally block is optional? I tested this myself, and
the following yield the same output.

Not always.
E.g. 1. If code1 throws an exception not catched by your catch statement
then code2 is not executed in your second example.
E.g. 2. If your catch statement throw an exception
then code2 is not executed in your second example.
E.g. 3. etc...

- Dario
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top