java: Exceptions: always reach finally? [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Does a finally block always run?
let's imagine the following scenario:
public void myMethod() throws MyException
try
{
// do something
// an Exception (for example an individual written MyException which extends
// "Exception" is thrown here
}
catch (OtherException e)
{
// do something
}
finally
{
// do something else
}
}
In case "MyException" is thrown in the try block and would not be catched - they finally block would be reached nonetheless, correct?
What if it would be an Runtime Exception, which would be thrown? Would the finally block be reached?
Is there any case where a finally block won't be reached?
Thanks for an answer :-)

Finally is always called unless you have a vm crash or call System.exit.

Related

Why an exception thrown from finally block ignores an exception thrown from catch block? [duplicate]

This question already has answers here:
Exception thrown in catch and finally clause
(12 answers)
Closed 4 years ago.
Can anyone give me a reason why new Exception() is ignored here?
void bar() throws IOException { //no Exception declared, compilator is ok about that. Why?
try{
throw new EOFException();
}
catch(EOFException eofe){
throw new Exception();
}
finally{
throw new IOException();
}
}
The finally block is always executed, regardless of whether the try block throws an exception or not (and regardless of whether it has a return statement or not).
Therefore, the exception thrown by the finally block - IOException - is the only exception thrown by your method, and it's always thrown, regardless of the content of the try block. Therefore your method only has to declare that it throws IOException.

What is the purpose of finally if it always executes in java? [duplicate]

This question already has answers here:
What is the benefit to use "finally" after try-catch block in java? [closed]
(6 answers)
Closed 5 years ago.
Consider the following Java snippets:
try{
//Some code to tryout
}
catch(Exception e){
//Catch if there is an exception
}
finally{
//SNIPPET1 that is always executed
}
The above snippet is essentially equal to
try{
//Some code to tryout
}
catch(Exception e){
//Catch if there is an exception
}
//SNIPPET1 that is always executed
I know that finally block is usually used to close network connections, file streams etc. I do not see a strong motivation in introducing this keyword into the language because one can happily program without using it as well.
Can you please explain the rationale behind introducing this keyword?
try {
// statement 1
} catch (Exception e) {
// statement 2
}
// statement 3
statement 3 won't be executed if statement 2 throws an exception

Exception handling without try block [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I think this is correct... When an exception occurs an object of the exception class is thrown and if we dont use a try or catch block, then the object goes to the JVM.
My question is why is the try block necessary, why wouldn't a catch block be good enough since the exception object is not created in the try block? I know that java requires you to use a try block to test the code in which the exception might occur, but was wondering if the exception object is created either way, then why couldn't a catch block been sufficient enough. This question is different from other exception handling questions in that it doesn't appear anyone has asked about needing to have the try block specifically.
The try { } portion indicates the section of code the catch { } block is protecting.
void test() {
do_something(); // Not covered
try {
something_fixable(); // Covered
} catch (InvalidStateException ex) {
do_recovery_for_fixable_thing();
}
}
Without the try { } block, the catch { } block might try to catch an exception other than the one it can handle.
Even if the exception thrown by do_something() is the same kind of exception, an InvalidStateException, the recovery code won't handle it; it isn't supposed to.
Suppose you had the following
doSomething(); // throws Exception1
doNothing(); // throws Exception2 which extends Exception1
catch(Exception 1 ex){ // handle exception }
To what does the catch block apply? Will it act only if an exception is thrown in doNothing()? Or will it also apply to the call to doSomething(). Or perhaps it will only apply to doSomething() and not doNothing(), which throws Exception2.
There is precedent for the omission of brackets. For example consider the next 2 groups of code.
int i;
for( i = 0 ; i < 10 ; i++)
System.out.println("hello World" + i);
and
int i;
for( i = 0 ; i < 10 ; i++)
{
System.out.println("hello World" + i);
}
Here the for statement is understood to act either on the next bracketed block or next single line of code.
So I suppose it might have been possible to have catch statements work on the previous statement or on the previous block. But that is just syntactic sugar, right? There is no functionality that you lose by requiring a try block.

Why does an empty try block with catch Exception compile? [duplicate]

This question already has answers here:
Java unreachable catch block compiler error
(7 answers)
Closed 7 years ago.
A try block without any code :
try {
} catch (Exception ex) {
// what Exception it is catching
ex.printStackTrace();
}
The absence of any code means that throwing an exception is impossible, so why doesn't this give an "unreachable catch block" compile error?
Exception includes RuntimeExceptions, which are unchecked and don't need to be declared, so Exception can always be validly caught.
I think this is an unimportant edge case.
That's valid Java syntax. It's the same as having an empty if-block:
if (condition) {
}
... or defining an empty method:
public void empty() {
}
... or only having comments as part of the body:
try {
// try body
} catch (Exception e) {
// catch body
}
All of that is valid syntax, so the compiler is happy. Further, since a blank line / empty body is totally ok, no exceptions will be thrown in the body of the try block during runtime, so the code would execute just fine as well.
So I am assuming that your question is what Exception will get caught and the answer is none. The exception would only be caught if while running the code within the try block throws an exception. It will then check to see if that exception was caught (FYI Exception will catch all exceptions), if yes it handles it inside the catch block otherwise it causes an error. Since there is nothing in the try block the exception will never be caught because no exception can ever be thrown.

Unhandled Java exception execute remainder of method?

I was responding to a slough of basic Java practice test questions and the correct answer to the following question slipped past me while taking the test.
Question: "If an exception is not caught, the finally block will run and the rest of the method is skipped - TRUE or FALSE?"
I am attempting to prove out the answer with the ThrowTest class (pasted at bottom) but I find Java exception handling to be somewhat unfamiliar. I compile the class as is with the ArrayIndexOutOfBoundsException portion of the catch block commented out. I then execute the class without passing an input parm thus creating an exception (the ArrayIndexOutOfBoundsException exception) . I would expect the final System.out.println would not execute and indeed it does not.
I find if I un-comment the ArrayIndexOutOfBoundsException catch block and recompile, the class then catches that specific error at run time and executes the "Rest of method" println at bottom. So, does my code prove the rest of "the rest of the method is skipped" or do I have to test it from a method other than the main method? Maybe there is a more straightforward method of testing it.
public class ThrowTest
{
public static void main(String[] args)
{
try
{
String anyString = args[0];
System.out.println("Try code executes");
}
catch(SecurityException e) //any old exception
{
System.err.println ("Error: SecurityException. ");
e.printStackTrace();
}
/* begin comment
catch(ArrayIndexOutOfBoundsException e)
{
System.err.println("Error: Caught ArrayIndexOutOfBoundsException. ");
e.printStackTrace();
}
end comment */
finally
{
System.out.println("finally block executes!");
}
System.out.println("Rest of method executes!");
}
}
Regardless of what exception is thrown a finally block will always execute (barring any strange situations like out of memory), so given the following
try {
// do some code
}
catch (SomeException e) {
// exception handling
}
finally {
doFinallyStuff();
}
doOtherStuff();
doFinallyStuff will always execute here. But doOtherStuff will only execute under the following conditions:
No exceptions are thrown
SomeException is thrown and the catch block does not rethrow the exception up the chain
If another exception is thrown in the try block that is not handled by the catch block, doFinallyStuff will still execute, but doOtherStuff will not
Your code is indeed proving that everything works as you described. When you catch an exception, then the rest of the method thereafter executes. If you let the method throw the exception, its execution halts immediately. Either way, the finally block will always execute.

Categories