Hi,
If you have a method that throws some Exception lik this:
public void doSomething(){throws SomeException
Do you then need a finally block in that method, if you i.e want to
close streams and such. I mean when this Exception occurs do it jump
out of the method direct or does it finish the rest of the method.
I wonder cause i tried to have a finally block in a method that did
not have any try and catch blocks så the compiler complained.
Best Regards
/Tomas
The best way to understand the program flow when using exceptions is just
to try it out. Set output statements everywhere you can, and then
examine what you get. Something like this:
public static void method1() throws Exception
{
System.out.println("method1 starts");
throw new Exception("exception in method1");
System.out.println("method1 ends");
}
public static void main(String args[])
{
System.out.println("main starts");
try
{
method1();
}
catch(Exception e)
{
System.out.println("exception caught");
e.printStackTrace();
}
finally
{
System.out.println("finally block executes");
}
System.out.println("main ends");
}
Here you will see that the "method1 ends" output will never be reached,
because the program flow is interrupted by the Exception. If you comment
out (or remove) the throw line, method1 will end normally, and the
"exception caught" line will be skipped. In either case the finally
block will be executed though.
You can never have a catch or finally block without a try block.
If you open resources locally in method1, it is best to do something like
this:
public void method1() throws Exception
{
SomeResource resource = null;
try
{
// open and use the resource
}
finally
{
if(resource == null)
resource.close();
}
}
Here the resource will be closed, wether or not an exception occurs,
because the finally block always executes. Since you're not catching any
exceptions, they will be thrown to be handled by the calling method.
Of course ideally you should not use Exception, but a subclass of it.