This question already has answers here:
Exception thrown inside catch block - will it be caught again?
(9 answers)
Closed 6 years ago.
I've come across an exercise while preparing my OCA, i don't understand why the program print : abce 3 instead of abcde 3. Here the program :
'public static void main(String[] args) {
System.out.print("a");
try{
System.out.print("b");
throw new IllegalArgumentException();
}catch(IllegalArgumentException e){
System.out.print("c");
throw new RuntimeException("1");
}catch(RuntimeException e) {
System.out.print("d");
throw new RuntimeException("2");
}finally {
System.out.print("e");
throw new RuntimeException("3");
}
}'
Any explanations why it ignores the last catch block will be really appreciated!
A finally block is always executed after a try-catch block, therefore e is printed. abc are obvious, as you throw an exception in try and the corresponding catch block for IllegalArgumentException is entered.
However, since you throw a new exception RuntimeException inside the catch block, it is thrown to the caller of your method. The catch blocks only handles exceptions thrown in a try block, all others are passed on to the caller of the function you throw the exception in.
Related
This question already has answers here:
How do I fix a compilation error for unhandled exception on call to Thread.sleep()?
(2 answers)
Closed 3 years ago.
I am writing a selenium code.
Unless I put the Thread.Sleep in a try catch block it won't work. It actually throws a compile time error.
Why so?
public void test() {
System.out.println("in the test method");
achromeDriver.get(abaseUrl);
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
WebElement benzRadioBtn = achromeDriver.findElement(By.id("benzradio"));
benzRadioBtn.click();
WebElement benzCheckBox = achromeDriver.findElement(By.id("benzcheck"));
benzCheckBox.click();
System.out.println("Is ben radio button selected ? "+ benzRadioBtn.isSelected());
}
The Thread.sleep() method throws an InterruptedException. Whether or not this exception will actually get thrown is dependent on what happens during the execution of your java code, the method is just letting you know it could happen, and that you should handle it in some way.
One way to handle the exception is to put it inside a try catch block, so if the exception gets thrown, the program will still continue and the code inside the catch block will execute.
If you really don't want a try catch block (no idea why you wouldn't) you can add a throws declaration at the top of your method which would look something like this:
public void test() throws InterruptedException {
I would read up some more about java exceptions and how they work
https://stackify.com/specify-handle-exceptions-java/
https://www.geeksforgeeks.org/exceptions-in-java/
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.
enter code here
`class Rethrow
{
public static void genException()
{
int n[]={4,8,16,32,64,128};
int d[]={2,0,8,0,4};
for(int i=0;i<n.length;i++)
{
try{
System.out.println("n/d is:"+n[i]/d[i]);
}
catch(ArithmeticException exc)
{
System.out.println("Cant Divide By Zero");
throw exc;
}
catch(ArrayIndexOutOfBoundsException exc)
{
System.out.println("No match element found ");
// rethrow the exception
}
}
}
}
class RethrowDemo
{
public static void main(String args[])
{
try
{
Rethrow.genException();
}
catch(ArithmeticException exc) // catch the rethrow Exception
{
// recatch exception
System.out.println("Fatal Error "+"Program Termiated.");
}
}
}
Question 1::why does catch of "RethrowDemo" CLASS terminate an exception thrown by catch(Arithmetic Exception) of "Rethrow" class.
Question 2:: how does transfer of control working ??
In Java, when an event occurs that disrupts the normal flow of your application an Exception object is created and it is passed up the call stack to either be dealt with by the caller or passed further up to be dealt with/handled by something else higher up in the hierarchy.
Due to the fact you can't divide by zero an ArithmeticException is thrown from the line System.out.println("n/d is:"+n[i]/d[i]); and since you're doing this within a try...catch block, your catch(ArithmeticException exc) says "If there is an ArithmeticException thrown from within the try then I'm here to deal with it".
It is in this catch block you are printing out Cant Divide By Zero and then re-throwing the original exception. This then bubbles up to the calling method, in your case to the main method but since you are making the call from within a try...catch(ArithmeticException exc) that catch in main says "I will deal with that ArithmeticException that you have just re-thrown". It is at this point you then print Fatal Error Program Termiated and the application ends.
There are plenty of tutorials that will explain fully how exceptions work in Java so it would be useful to take a look at a few.
A Tutorial on Exceptions
Another Tutorial on Exceptions
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.
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!