I'm writing a loop that ignored the Exception and it works well.
for (; flag; ) {
try {
//do something ignore exception.
Runnable r = queue.pollFirst();
r.run();
} catch (Exception ignored) {
// ignored.
}
}
But my question is: If I don't catch RuntimeException and force continue loop in finally block, what will happen to the Exception and returned value?
Example:
for (int i = 0; i < 10; i++) {
try {
System.out.println(i);
throw new RuntimeException();
} finally {
//what will happen to the exception if continue loop?
continue;
}
}
They will be ignored as the finally block has the final word.
Runtime Exception will be ignored because there is no catch block to access/use (e.g. for logging purpose) thrown object of java.lang.RuntimeException. finally block does not have any access to Exception object thrown by try block. Its better to have catch block to get more information.
Not sure why you would want to catch a RuntimeException because by the time you even try catching it, it's too late therefore your continue will never hit.
Related
This question already has answers here:
Why use finally instead of code after catch [duplicate]
(14 answers)
Closed 5 years ago.
What is the significance of the Finally block in a Try...[Catch]...Finally block?
Isn't this code
Resource r;
try{
r = new Resource();
r.methodThatThrowsException();
} catch (Exception e) {
e.printStackTrace()
} finally {
r.close()
}
equivalent to
Resource r;
try{
r = new Resource();
r.methodThatThrowsException();
} catch (Exception e) {
e.printStackTrace()
}
r.close()
? I would understand if they have the same scope, but the fact that I have to define Resource r outside the try block anyway to use it in the finally block means that I see no advantage to using a finally block.
Am I missing something? Is there a certain case that I haven't thought of that requires a Finally block?
In this case, they are equivalent since (a) the code catches any exception, including runtime exceptions that are thrown and (b) the catch block doesn't rethrow the exception, so the execution continues.
The finally block is generally used to ensure resource release in cases where either (a) or (b) don't hold. In newer Java implementations, wherever possible, you should use try-with-resources instead.
The two code snippets are different: the second one will not close if exception handling block ends in another exception.
Here is an illustration:
public static void one() throws Exception {
try {
System.out.println("One");
throw new Exception();
} catch (Exception e) {
System.out.println("Catch one");
if (2 != 3) throw new Exception(); // "if" silences compiler's check
} finally {
System.out.println("Finally one");
}
}
public static void two() throws Exception {
try {
System.out.println("Two");
throw new Exception();
} catch (Exception e) {
System.out.println("Catch two");
if (2 != 3) throw new Exception(); // "if" silences compiler's check
}
System.out.println("After two");
}
The call to one() prints Finally one, while After two never gets printed (demo 1).
The finally block becomes even more important when you catch specific exceptions (blindly catching Exception is nearly always a bad idea), because the try block may bypass your cleanup code by throwing an exception that you do not catch. Here is another illustration:
public static void error() throws Exception {
try {
System.out.println("Try");
throw new Error();
} catch (Exception e) {
System.out.println("Catch");
throw new Exception();
} finally {
System.out.println("Finally");
}
}
This code prints Try and Finally, without Catch in the middle, because Error is not caught in the catch block (demo 2).
It goes without saying that human readers of your program will have easier time locating you clean-up code if you place it in the finally block.
No, it is not equivalent. In the first snippet r.close() will be always called, while in the second snippet r.close() might not be called:
when the try block throws an Error (what might happen when you use assertions and an assertion fails)
when the exception handler throws another Exception
To ensure the resources are always released close() method should be called from finally blocks.
I know that try statement is useless without catch or finally, and the finally clause is optional in a try-catch block. However, when I write a try statement without catch or finally, the compiler suggests inserting finally clause to complete try statement.
For example:
try {
for (int j = 0; j <= i.length; j++) {
System.out.println(i[j]);
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Catch");
} //no errors
try {
for (int j = 0; j <= i.length; j++) {
System.out.println(i[j]);
}
} //syntax error
Error code:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error, insert "Finally" to complete TryStatement
at Driver.main(Driver.java:12)
Why is finally the only recommended statement to implement? Why not catch?
"I might want something to happen despite an exception being thrown, so I may not be looking to handle a specific exception in a specific way, but I may want to ensure that at least SOMETHING generic happens. If I can't handle it, at least do something." Looking for somebody to confirm on this.
Because a try without a catch or a finally makes no sense at all. It just does nothing so you'd have the same result if you just omit the try-block.
It's required that a try statement has either a catch or finally clause because it would make very little sense in having a try statement without it.
The whole idea with the try statement is that there is some kind of handling to be done if the try-block throws exception. This handling can either be to catch an exception (using catch) or do something after the block has finished or an exception has been thrown (using finally). Then to have no such action associated with the try statement makes the try statement pointless.
finally guarantees the code in finally block always execute no matter there's exceptions or not, and you can write cleancode in finally block except handling exceptions, for example close a file or close a socket in it. try-catch is for a caught exception that you can fix it locally.
You cannot have a try not followed by a catch or a finally
In order to fix it add a catch or a finally or both like this:
try{
for(int j = 0; j <= i.length; j++)
{
System.out.println(i[j]);
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Catch");
}//no errors
try{
for(int j = 0; j <= i.length; j++)
{
System.out.println(i[j]);
}
}//syntax error
catch(Exception e) {
// ... handle errors ...
} finally {
// ... cleanup that will execute whether or not an error occurred ...
}
This question already has answers here:
Exception thrown in catch and finally clause
(12 answers)
Closed 9 years ago.
When I am executing following code
1. public class test {
2. public static void main(String[] args) {
3. try {
4. int i = 10 / 0;
5. } catch (Exception e) {
6. int j = 10 / 0;
7. } finally {
8. int k = 10 / 0;
9. }
10. }
11. }
I am getting an error:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at test.main(test.java:8)
I am not getting the reason why JVM is throwing exception from main() and not the catch block.
If you follow the step-by-step description of a try-catch-finally in the JLS, you see that (in summary) if catch throws an exception then finally is executed and (emphasis mine):
If the catch block completes abruptly for reason R, then the finally block is executed.
If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).
So the exception thrown by the catch block (which is executed before the finally block) is discarded and the reported exception is the one thrown in the finally block.
Because in every block - try/catch/finally you have a division by zero. Add another try-catch block inside catch and report an error in catch.
For example:
public class test {
public static void main(String[] args) {
try {
int i = 10 / 0;
} catch (Exception e) {
try {
int j = 10 / 0;
} catch (Exception e) {
// report an error here - do not do any business logic
}
} finally {
int k = 10 / 0;
}
}
}
One interesting thing to note is that, if you comment your code in the finally statement, the ArithmeticException thrown will concern the code in your catch statement.
I believe what's happening here is that the Exception that should be thrown in your catch statement is ignored, because an Exception is thrown in your finally statement.
The exception
in } catch (Exception e) {
int j = 10 / 0;
}
will be thrown to finally block, if you remove finally block, you will got an
Exception in thread "main" java.lang.ArithmeticException: / by zero
at test.main(test.java:6)
All exception in catch block will be thrown to finally block
also finally block will be executed any way
try
{
System.out.println("Try block 1");
int i = 10 / 0; //First Exception
System.out.println("Try block 2");
} catch (Exception e) { //Catched the first Exception
System.out.println("Catch block 1");
int j = 10 / 0; //Again Exception --> Who will catch this one
System.out.println("Catch block 2");
} finally {
System.out.println("finally block 1");
int k = 10 / 0; //Again Exception --> Who will catch this one
System.out.println("finally block 2");
}
If an exception occurs within the try block, that exception is handled by an exception handler associated with it. To associate an exception handler with a try block, you must put a catch block after it.
You associate exception handlers with a try block by providing one or more catch blocks directly after the try block.
Each catch block is an exception handler and handles the type of exception indicated by its argument
The finally block always executes when the try block exits.
In Java Exception Handling, no matter the exception is caught or not, but if you have used finally block, it would always get executed.
Hence, what you are doing in your code is-
Throwing exception object from main()
Catching exception in catch block
Throwing exception caught in catch block to the finally block (it would get executed anyway!)
In this code, either you use only catch or only finally, to get proper result.
and, since you want exception to be caught in catch, omit finally, just use catch.
Good luck!
This may seem like a programming 101 question and I had thought I knew the answer but now find myself needing to double check. In this piece of code below, will the exception thrown in the first catch block then be caught by the general Exception catch block below?
try {
// Do something
} catch(IOException e) {
throw new ApplicationException("Problem connecting to server");
} catch(Exception e) {
// Will the ApplicationException be caught here?
}
I always thought the answer would be no, but now I have some odd behaviour that could be caused by this. The answer is probably the same for most languages but I'm working in Java.
No, since the new throw is not in the try block directly.
No. It's very easy to check.
public class Catch {
public static void main(String[] args) {
try {
throw new java.io.IOException();
} catch (java.io.IOException exc) {
System.err.println("In catch IOException: "+exc.getClass());
throw new RuntimeException();
} catch (Exception exc) {
System.err.println("In catch Exception: "+exc.getClass());
} finally {
System.err.println("In finally");
}
}
}
Should print:
In catch IOException: class java.io.IOException
In finally
Exception in thread "main" java.lang.RuntimeException
at Catch.main(Catch.java:8)
Technically that could have been a compiler bug, implementation dependent, unspecified behaviour, or something. However, the JLS is pretty well nailed down and the compilers are good enough for this sort of simple thing (generics corner case may be a different matter).
Also note, if you swap around the two catch blocks, it wont compile. The second catch would be completely unreachable.
Note the finally block always runs even if a catch block is executed (other than silly cases, such as infinite loops, attaching through the tools interface and killing the thread, rewriting bytecode, etc.).
The Java Language Specification says in section 14.19.1:
If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:
If the run-time type of V is assignable to the Parameter of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed. If that block completes normally, then the try statement completes normally; if that block completes abruptly for any reason, then the try statement completes abruptly for the same reason.
Reference:
http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html#24134
In other words, the first enclosing catch that can handle the exception does, and if an exception is thrown out of that catch, that's not in the scope of any other catch for the original try, so they will not try to handle it.
One related and confusing thing to know is that in a try-[catch]-finally structure, a finally block may throw an exception and if so, any exception thrown by the try or catch block is lost. That can be confusing the first time you see it.
If you want to throw an exception from the catch block you must inform your method/class/etc. that it needs to throw said exception. Like so:
public void doStuff() throws MyException {
try {
//Stuff
} catch(StuffException e) {
throw new MyException();
}
}
And now your compiler will not yell at you :)
No -- As Chris Jester-Young said, it will be thrown up to the next try-catch in the hierarchy.
As said above...
I would add that if you have trouble seeing what is going on, if you can't reproduce the issue in the debugger, you can add a trace before re-throwing the new exception (with the good old System.out.println at worse, with a good log system like log4j otherwise).
It won't be caught by the second catch block. Each Exception is caught only when inside a try block. You can nest tries though (not that it's a good idea generally):
try {
doSomething();
} catch (IOException) {
try {
doSomething();
} catch (IOException e) {
throw new ApplicationException("Failed twice at doSomething" +
e.toString());
}
} catch (Exception e) {
}
No, since the catches all refer to the same try block, so throwing from within a catch block would be caught by an enclosing try block (probably in the method that called this one)
Old post but "e" variable must be unique:
try {
// Do something
} catch(IOException ioE) {
throw new ApplicationException("Problem connecting to server");
} catch(Exception e) {
// Will the ApplicationException be caught here?
}
Is there a way to detect, from within the finally clause, that an exception is in the process of being thrown?
See the example below:
try {
// code that may or may not throw an exception
} finally {
SomeCleanupFunctionThatThrows();
// if currently executing an exception, exit the program,
// otherwise just let the exception thrown by the function
// above propagate
}
or is ignoring one of the exceptions the only thing you can do?
In C++ it doesn't even let you ignore one of the exceptions and just calls terminate(). Most other languages use the same rules as java.
Set a flag variable, then check for it in the finally clause, like so:
boolean exceptionThrown = true;
try {
mightThrowAnException();
exceptionThrown = false;
} finally {
if (exceptionThrown) {
// Whatever you want to do
}
}
If you find yourself doing this, then you might have a problem with your design. The idea of a "finally" block is that you want something done regardless of how the method exits. Seems to me like you don't need a finally block at all, and should just use the try-catch blocks:
try {
doSomethingDangerous(); // can throw exception
onSuccess();
} catch (Exception ex) {
onFailure();
}
If a function throws and you want to catch the exception, you'll have to wrap the function in a try block, it's the safest way. So in your example:
try {
// ...
} finally {
try {
SomeCleanupFunctionThatThrows();
} catch(Throwable t) { //or catch whatever you want here
// exception handling code, or just ignore it
}
}
Do you mean you want the finally block to act differently depending on whether the try block completed successfully?
If so, you could always do something like:
boolean exceptionThrown = false;
try {
// ...
} catch(Throwable t) {
exceptionThrown = true;
// ...
} finally {
try {
SomeCleanupFunctionThatThrows();
} catch(Throwable t) {
if(exceptionThrown) ...
}
}
That's getting pretty convoluted, though... you might want to think of a way to restructure your code to make doing this unnecessary.
No I do not believe so. The catch block will run to completion before the finally block.
try {
// code that may or may not throw an exception
} catch {
// catch block must exist.
finally {
SomeCleanupFunctionThatThrows();
// this portion is ran after catch block finishes
}
Otherwise you can add a synchronize() object that the exception code will use, that you can check in the finally block, which would help you identify if in a seperate thread you are running an exception.