Catch Follows Finally block in java

Can a Catch block Follows Finally block in exception?

finally{
baz();
}catch(MyException e){}

Upvotes: 1

Views: 156

Answers (5)

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35547

You can check that by your own. Following scenarios are possible with try-catch-finally

case 1

 try{

    }catch(Exception e){

    }finally {

    }

case 2

    try{

    }finally {

    }

case 3

    try {

    }catch (Exception e){

    }

As you can see finally should come after try or catch. similarly finally can't be before catch.

Upvotes: 1

AllTooSir
AllTooSir

Reputation: 49352

No It can't . A try should be followed by a catch or finally . If there is a catch then finally is the last block. This order will again depend on nesting . So you can have a nested structure like below , but again try is followed by a finally or catch . The catch after the internal finally block belongs to the outer try.

try {
    // outer try
   try {
     // inner try
    }
    finally {
    }
 }
 catch(SomeException e) {
 }

You can read more about it in JLS 14.20.

Upvotes: 6

Juned Ahsan
Juned Ahsan

Reputation: 68715

The construct is called as try-catch-finally. Where try need to be followed by either catch or finally or both. If all the three are present, the finally block always executes when the try block exits no matter whether an exception has occured or not.

The reason why you are looking for a catch after finally is probably how to handle an exception in finally. There is no other way rather than putting another try/catch/finally block inside that :-(

Upvotes: 1

stinepike
stinepike

Reputation: 54672

Only for the following case it is possible

try{
   try{

   } finally{
   } 
   baz();
}catch(MyException e){}

But it is a totally different strucute. With the structure of your question it is not possible.

Upvotes: 1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Can a Catch block Follows Finally block in exception?

No, not if it's for the same try.
But you could find this out quickly by trying it with your trusty Java compiler.

Note, that having said this, you can nest try/catch blocks if need be, but again the catch block after the finally would be on a different scope level than the preceding finally.

I'm curious as to the instigation for this question. A finally() really must always be final, and always be called, else it is not a true finally. What are you trying to accomplish with this? Because I'll bet that there is a better way, that perhaps what you have is an XY problem, and that the solution is to try a completely different approach. Or is this a homework question?

Upvotes: 2

Related Questions