Java: Hypothetical question about finally block - java

What happens if you throw an error in a finally block? Does it get handled in one of the corresponding catch clauses?

Only if you put another try-catch block in the finally block. Otherwise it's an error like any other.

You need to include try-catch blocks inside the finally or catch blocks.
e.g.:
try {
// your code here
} finally {
try {
// if the code in finally can throw another exception, you need to catch it inside it
} catch (Exception e) {
// probably not much to do besides telling why it failed
}
} catch (Exception e) {
try {
// your error handling routine here
} catch (Exception e) {
// probably not much to do besides telling why it failed
}
}

It will not handle exception until it is caught in finally block it self.
public static void main(String[] args) throws Exception {
try {
System.out.println("In try");
} catch (Exception e) {
System.out.println("In catch");
} finally{
throw new Exception();
}
}
Above code will throw exception but if you do as follows it will work:
public static void main(String[] args){
try {
System.out.println("In try");
} catch (Exception e) {
System.out.println("In catch");
} finally{
try{
throw new Exception();
}catch(Exception e){}
}
}

Nope. It would be caught by a catch where then entire try/catch/finally was nested within another try/catch. The exception would otherwise be thrown out of the function, and would be handled by the caller of the function.

No it doesn't. You will have to handle with it IN the finally block or define a proper throw declaration in the method description.

No, a catch block can only catch exceptions thrown within the corresponding try block - not a finally block. (Of course, if that finally block is within another try block, the catch clauses for that try block are still used.)
The relevant section in the JLS is 14.20.2. Each of the flows listed there has something like this:
If the finally block completes abruptly for any reason, then the try statement completes abruptly for the same reason.
In other words, there's no attempt for any catch clauses associated with the finally block to handle the exception.

The order of execution is normally directly indicated by the order of statements: 1. try, 2. catch exceptions in the specified order (only one catch is executed), 3. finally.
So when the finally block is executed (note that this is always the case, even in the case of a return statement or exception being thrown in the try or catch blocks) the execution of try statement is in its last phase and thus it cannot catch further throwables. As already pointed out, the exception has to be handled in a location further down the stack (or up, depends on the view point ;) ).

Related

Is it possible to use Try catch block inside a catch block?

I have asked a question in aptitude test that a new try catch block can be inside a catch block or not?
For example
try {
} catch (Exception e) {
try {
} catch (Exception e) {
}
}
Is this valid in Java?
Yes it is possible tried following example with java8. it is working fine.
public static void main(String []args){
try{
System.out.println("try1");
throw new Exception("Exception1");
}catch(Exception e){
System.out.println("catch1");
try{
System.out.println("try2");
throw new Exception("Exception2");
}catch(Exception e1){
System.out.println("catch2");
}
}
}
Yes (given that you use upper/lower case correctly: try, catch, Exception)
Yes, It is possible because if any exception is occurs in try then it's catch and we want to add some logic or next implementation in catch block then we can.for example if we write code for get data in outer try block and getting any exception and we need add some logic like file releated or thread releated then we add and use try catch block in outer catch.

Exception Handling with Multiple catch block [duplicate]

This question already has answers here:
Order of catching exceptions in Java
(3 answers)
Closed 6 years ago.
Here is my program.
try {
int a = 1/0;
}
catch(Exception e) {
system.out.println("Exception block"+e);
}
catch(ArithmeticException e) {
system.out.println("Inside ArithmeticException block");
}
finally {
system.out.println("Inside Finally block");
}
In the above program i have two catch blocks and one finally block.
Which catch block will execute? Because I define the parent catch block first. So it leads to an error? Can any one help me?
I assumed that "ArithmeticException and Finally block will be executed"
Catching Exception class will not give any error. However, it is not recommended.
In this case, Exception catch block will execute first and then finally block will execute.
If you want that your ArithmeticException block should execute, put this block before Exception catch block.
Update code -
try{
int a = 1/0;
}
catch(ArithmeticException e){
System.out.println("Inside ArithmeticException block");
}
catch(Exception e) {
System.out.println("Exception block"+e);
}
finally{
System.out.println("Inside Finally block");
}
Catching Exception class will not give any error.
In this case, Exception catch block will execute first and then finally block will execute.
If you want that your ArithmeticException block should execute, put this block before Exception catch block.
Here is Updated code
try {
int a = 1/0;
}
catch(Exception e) {
System.out.println("Exception block"+e);
}
finally {
System.out.println("Inside Finally block");
}
}

How does exception chain work in my code?

Why this code doesn't print "d". Why it doesn't go to the catch block for RunTimeException?
public static void main(String[] args) {
System.out.println("a");
try {
System.out.println("b");
throw new IllegalArgumentException();
} catch (IllegalArgumentException e) {
System.out.println("c");
throw new RuntimeException();
}catch (RuntimeException e) {
System.out.println("d");
throw new RuntimeException();
}finally{
System.out.println("e");
throw new RuntimeException();
}
}
The output of this program is
a
b
c
e
Exception in thread "main" java.lang.RuntimeException
EDIT: After throwing IllegalArgumentException it goes to the corresponding catch block and prints 'c'. after that since we don't catch the exception in RuntimeException it doesn't go any further. but since it's guranteed that we go to the finally block it print 'e' and after that throw RunttimeException. if the code was like something like the following, it would throw out the RuntimeException("2"). If we comment the exception inside finally, it throw out RuntimeException("1").
public static void main(String[] args) throws InterruptedException {
System.out.println("a");
try {
System.out.println("b");
throw new IllegalArgumentException();
} catch (IllegalArgumentException e) {
System.out.println("c");
throw new RuntimeException("1");
}catch (RuntimeException e) {
System.out.println("d");
throw new RuntimeException();
}finally{
System.out.println("e");
throw new RuntimeException("2");
}
}
The reason of this code not printing d is, because in the IllegalArgumentException catch block, after printing "c" and before throwing RuntimeException it executes finally (that's how the flow works). Finally block throws exception itself, so It never gets to throw that RuntimeException that gets it to "d".
public static void main(String[] args) {
System.out.println("a");
try {
System.out.println("b"); // 1
throw new IllegalArgumentException(); // 2
} catch (IllegalArgumentException e) {
System.out.println("c"); // 3
throw new RuntimeException(); // nope, there's a finally block that executes first
}catch (RuntimeException e) {
System.out.println("d");
throw new RuntimeException();
}finally{
System.out.println("e"); // 4
throw new RuntimeException(); // 5 - rest of the code never got executed.
}
}
Hope this was clear enough.
Also, as it was pointed out, even if the RuntimeException after "c" was executed, It would not invoke the lower catch block. The catch block is only invoked once, depending on the Exception thrown in the try block (though this isn't really relevant because the first explanation dictates the flow of your thread).
The catch blocks are NOT in the scope of the try. Any code in the catch blocks executes in the context of the outer main code, and thus has no exception handlers. When you throw RuntimeException the finally block for the try gets executed and then the exception terminates the program.
In try catch block, if one of the catch block catches the exception the other catches doesn't get involved. remeber that finally block always run at the end no matter exception gets threw or not.

Where to put finally in nested try/catch?

How does finally work in nested try/catch?
E.g. for:
try{
//code
}
catch(SomeException e){
//code
try{
//code
}
catch(OtherException e){
//code
}
}
catch(SomeOtherException e){
//code
}
Where is the best place to put finally? Or should I put it in nested and outer try as well?
If you want the code in the finally block to run no matter what happens in either block, put it on the outer try. If you only want it to run no matter what happens within the first try block, put it there:
try{ // try/catch #1
//code block #1
}
catch(SomeException e){
//code block #2
try{ // try/catch #2
//code block #3
}
catch(OtherException e){
//code block #4
}
finally {
// This code runs no matter what happens with try/catch #2 (so
// after code block #3 and/or #4, depending on whether there's
// an exception). It does NOT run after code block #1 if that
// block doesn't throw, does NOT run after code block #2 if
// that block DOES throw), and does not run if code block #1
// throws SomeOtherException (code block #5).
}
}
catch(SomeOtherException e){
//code block #5
}
finally {
// This code runs no matter what happens with EITHER
// try/catch #1 or try/catch #2, no matter what happens
// with any of the code blocks above, 1-5
}
More briefly:
try {
// covered by "outer" finally
}
catch (Exception1 ex) {
// covered by "outer" finally
try {
// Covered by both "inner" and "outer" finallys
}
catch (Exception2 ex) {
// Covered by both "inner" and "outer" finallys
}
catch (Exception3 ex) {
// Covered by both "inner" and "outer" finallys
}
finally { // "inner" finally
}
}
catch (Exception4 ex) {
// covered by "outer" finally
}
finally { // "outer" finally
}
It depends on the place where you want the code in finally block to execute.
try{ //Try ROOT
//code
}
catch(SomeException e){ //Catch ROOT ONE
//code
try{ //Try NEST
//code
}
catch(OtherException e){ //Catch NEST
//code
}
finally{
//This will execute after Try NEST and Catch NEST
}
}
catch(SomeOtherException e){ //Catch ROOT TWO
//code
}
finally{
//This will execute after try ROOT and Catch ROOT ONE and Catch ROOT TWO
}
There is no best place it's dependent on the functionality you desire. But if you want the finally block to run only after all the try catch blocks then you should place it after the final root catch block.

question about try-catch

I have a problem understanding how the try{} catch(Exception e){...} works!
Let's say I have the following:
try
{
while(true)
{
coord = (Coordinate)is.readObject();//reading data from an input stream
}
}
catch(Exception e)
{
try{
is.close();
socket.close();
}
catch(Exception e1)
{
e1.printStackTrace();
}
}
Section 2
try
{
is.close();
db.close();
}
catch(Exception e)
{
e.printStackTrace();
}
Let's say my while() loop throws an error because of an exception of is stream.
This will get me out of the infinite loop and throw me in the first catch(){............}
block.
My question is the following:
After throwing an exception, getting out of the loop while() and reaching to
catch(){
}
Will my program continue his execution and move on to section 2? As long as the exception was caught? Or everything ends in the first catch()?
I think you want to use finally after your first catch [catch (Exception e)] to close your streams:
try {
// Do foo with is and db
} catch (Exception e) {
// Do bar for exception handling
} finally {
try {
is.close();
db.close();
} catch (Exception e2) {
// gah!
}
}
As long as no exceptions are thrown in your catch clause, your program will continue execution after your catch (or finally) clause. If you need to rethrow the exception from the catch clause, use throw; or throw new Exception(ex). Do not use throw ex, as this will alter the stack trace property of your exception.
After the exception is caught, execution continues after the try/catch block. In this case, that's your section 2.
An uncaught exception will terminate the thread, which might terminate the process.
Yes, you are right. It will move to Section 2.
If you want your Section 2 bound to happen, irrespective of any exception generated, you might want to enclose them in a finally block.
try {
// Do foo with is and db
}
catch (Exception e) {
// Do bar for exception handling
}
// Bound to execute irrespective of exception generated or not ....
finally {
try {
is.close();
db.close();
}
catch (Exception e2) {
// Exception description ....
}
}

Categories

Resources