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!
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'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.
This might be a really dumb question to most of you here, really sorry about that. I am new to java and the book i am reading didn't explain the working of an example in it.
public class CrazyWithZeros
{
public static void main(String[] args)
{
try
{
int answer = divideTheseNumbers(5, 0);
}
catch (Exception e)
{
System.out.println("Tried twice, "
+ "still didn't work!");
}
}
public static int divideTheseNumbers(int a, int b) throws Exception
{
int c;
try
{
c = a / b;
System.out.println("It worked!");
}
catch (Exception e)
{
System.out.println("Didn't work the first time.");
c = a / b;
System.out.println("It worked the second time!");
}
finally
{
System.out.println("Better clean up my mess.");
}
System.out.println("It worked after all.");
return c;
}
}
I can't figure out where the control will go after another exception is generated in catch block in divideTheseNumbers() method ?
Any help will be appreciated !
Output for your program will be
Didn't work the first time.
Better clean up my mess.
Tried twice, still didn't work!
Didn't work the first time. - because of the catch block in divideTheseNumbers
Better clean up my mess. - because of the finally block in divideTheseNumbers
Tried twice, still didn't work! - because of the catch block in the main method.
In general when a exception is thrown from a method and if is not in a try block, it will be thrown to it's calling method.
There are two points to note :
1) Any exception that is not in a try block will be just thrown to
it's calling method(even if it is in a catch block)
2) finally block is always executed.
In your case, you are getting the second exception in catch block, so it will be thrown. But before exiting any method it will also execute finally block(finally block is always executed). That is why Better clean up my mess is also printed.
Some points regarding exception handling:
1. Place your code that may causes exception inside the try{} block.
2. Catch the appropriate exception using the catch block.
3. While catching exception it's better use more specific type exception instead of catching the generic exception like. For example you catch the Exception, in this case you may catch the more specific type exception ArithmeticException.
4. finally block always executed, even though you use return statement in catch or try block.
5. A method either throws or catch an exception. If a method catch an exception then for it is not required to throws the exception.
6. All exception need not to be handled by using catch-block. We can avoid the try-catch block for the unchecked exception like - ArithmeticException,NullPointerException, ArrayIndexOutOfBoundsException. See here for more.
You may also check the tutorial for learning more about exception handling.
public class CheckProg {
public int math(int i) {
try {
int result = i / 0;
// throw new IOException("in here");
} catch (Exception e) {
return 10;
} finally {
return 11;
}
}
public static void main(String[] args) {
CheckProg c1 = new CheckProg();
int res = c1.math(10);
System.out.println("Output :" + res);
}
Question: If I run the above code, I get the result as Output: 11
Why? Shouldn't the exception be caught before in the catch block and returned?
Shouldn't the exception be caught before in the catch block and returned ?
It is being caught, and that return statement is being executed... but then the return value is being effectively replaced by the return statement in the finally block, which will execute whether or not there was an exception.
See JLS 14.20.2 for details of all the possibilities. In your case, this is the path:
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 assignment compatible with a catchable exception class 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. Then there is a choice:
If the catch block completes normally [ ... ignored, because it doesn't ]
If the catch block completes abruptly for reason R, then the finally block is executed. Then there is a choice:
If the finally block completes normally [ ... ignored, because it doesn't ]
If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).
So that bottom line is the important one - the "reason S" (in our case, returning the value 11) ends up being the way that the try statement completes abruptly.
Yes. But the finally block is always executed afterwards and overrules the return value!
Finally block gets executed whether or not an exception occurs.
It is pretty much self-explanatory. Catch block is executing because there is an exception. Finally will execute as its execution is guaranteed irrespective of an exception.
Note - If you have given some other statement(s) instead of return, both statements have been executed. but in case of return, only last return is being executed.
} catch (Exception e) {
System.out.println("10");
} finally {
System.out.println("11");
}
The "finally" keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred.
try
{
final int x=100;
System.out.println("The value of x is"+ x);
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
System.out.println("Finally Block executed");
}
Which exception handler going to handle the exception if there is no catch block ?
public class Doubt {
public static void main(String arg[])
{
System.out.println("hi");
int i=10;
int j;
try
{
j=i/0;//Arithmatic exception type object is created but no catch block so who will catch d exception..
}
finally
{
System.out.println("shit");
}
System.out.println("program still running");
}
}
None. The try..finally block doesn't catch exceptions at all.
It is used to ensure that the code in the finally block gets executed (even when an exception in the try block occurs). The finally block will always get executed, even when there is a return statement in try.
Short from cutting power from your computer or suddenly shutting JVM down (or in some cases interrupting a thread in which the try code was executed) there is no way to skip the finally block.
Add a catch block to catch an exception:
try {
j=i/0;
} catch(Excecption e) {
e.printStackTrace();
} finally {
System.out.println("shit");
}
There are three types of Exceptions in Java:
Checked - you are forced to use try catch block, if you do not do that - your program will not compile
Unchecked (Runtime Exceptions) - these exception are thrown by jre. As in your example you cannot determine everything at compile time. Instead of your i/0 there could be some number divided by user input. When user passes 0 - you will get runtime exception. Unhandled will crash application.
Error - Generally this is almost the same as above, but this is connected to jvm failures, like memory corruption etc.
The JVM system will catch the exception and crash ungracefully. Add an except statement to either handle the exception or exit gracefully.
Try block
The try block contains set of statements where an exception can occur. A try block is always followed by a catch block, which handles the exception that occurs in associated try block. A try block must be followed by catch blocks or finally block or both.
Catch block
A catch block is where you handle the exceptions, this block must follow the try block. A single try block can have several catch blocks associated with it. You can catch different exceptions in different catch blocks. When an exception occurs in try block, the corresponding catch block that handles that particular exception executes. For example if an arithmetic exception occurs in try block then the statements enclosed in catch block for arithmetic exception executes.
https://beginnersbook.com/2013/04/try-catch-in-java/ getsome idea from this..