Catch Follows Finally block in java - java

Can a Catch block Follows Finally block in exception?
finally{
baz();
}catch(MyException e){}

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.

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?

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.

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 :-(

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.

Related

Why do we need "try" keyword?

Today I wrote some Java which was structured something like this:
if (someCondition) {
try {
doSomething();
} catch (SomeException e) {
handleException(e);
}
}
It looked somewhat ugly so I decided to remove excesss {}-block from it.
if (someCondition) try {
doSomething();
} catch (SomeException e) {
handleException(e);
}
Which made me think that the try keyword is actually redundant. Isn't catch or finally after {}-block enough to inform the compiler / programmer that exceptions thrown inside the block have special handling?
EDIT: To clarify I don't mean that the whole try block is redundant. Just that the try keyword is. Above example would be written as:
if (someCondition) {
doSomething();
} catch (SomeException e) {
handleException(e);
}
EDIT: As requested here is a example method without if:
public void someMethod() {
{
doSomething();
} catch (SomeException ex) {
handleException(e);
}
}
Again, clear without the try keyword.
As per Java Syntax : catch block should be associated with try block as per java syntax.
IF you do not write try and write only catch block then java compiler throws error.
Why is it designed so : why we need to associate every catch/finally block with try is to write exception specific code that should be executed in case of exception in the associated try block.
If java is designed to proceed without try block then programmer does not know what specific code to be written catch block and ends up writing fallback code for all kinds of exceptions in one catch block resulting in execution of all catch block code for any kind of exception.
Also as per your doubt that placement of catch block, if you don't write try then catch block (if designed so by Java designers) has to handle exception generated in the entire code written above it which leads to the scenario explained in the above paragraph.
So, it is better to have code which may generate exception and associate with catch block which can have specific code to handle that exception.It is also the same purpose of writing multiple catch blocks after try block, with most specific or possible exception in first catch block and having the generic catch exception block at the last.
The Try block lets the catch block now what is going on inside of him .

try/catch block return with finally clause in java [duplicate]

This question already has answers here:
Does a finally block always get executed in Java?
(51 answers)
Closed 9 years ago.
Given the following try/catch block in java:
try{
return;
}
catch(SomeException e){
System.out.println(e);
}
finally{
System.out.println("This is the finally block");
}
and according to this post: "Does finally always execute in Java?" I can see that the program's output will be 'This is the finally block'. However, I can't figure out how that would be possible since the print statement is preceded by a return...
I suspect that this behaviour has something to do with threading, however I am not certain. Please enlighten me. Thank you.
finally is executed before return statement. As java rule finally will always be executed except in case when JVM crashes or System.exit() is called.
Java Language Specification clearly mentions the execution of finally in different conditions:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.20.2
return statement has no effect on the execution of finally block. The only way a finally block isn't executed is in case if JVM crashes/exits before executing finally block. Check this Link for more. So, if your code is replaced by
try{
System.exit(0);
}
catch(SomeException e){
System.out.println(e);
}
finally{
System.out.println("This is the finally block");
}
The finally block won't execute
Juned is correct. I also wanted to caution about throwing exceptions from finally blocks, they will mast other exceptions that happen. For example (somewhat silly example, but it makes the point):
boolean ok = false;
try {
// code that might throw a SQLException
ok = true;
return;
}
catch (SQLException e) {
log.error(e);
throw e;
}
finally {
if (!ok) {
throw new RuntimeException("Not ok");
}
}
In this case, even when an SQLException is caught and re-thrown, the finally throws a RuntimeException here and it it will "mask" or override the SQLException. The caller will receive the RuntimeException rather then the SQLException.

Should you catch all exceptions in your main method

Is it correct to catch everything into the main? If not, why?
public static void main(String[] args) {
try {
// A lot
// of
// calls
} catch (Exception e) {
e.printStackTrace();
}
}
Generally it's better to separate out the catches IMO, so that you can handle each separately even if you end up handling these the same. It's also easier to see what the risks are, what the catch is, when you come back to your code. Just a quick example:
try {
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (IOException e) {
request.abort();
} finally {
client.close();
}
If all you do is call e.printStacktrace (), I do not think it is worthwhile. The JVM will do something like that anyway. But I believe it is worthwhile if you output a meaningful message; stacktraces are meaningful only to programmers.
It will catch every Exception from the try{} block, It might not catch if there is another catch catching in the inner code
It depends. If you only need to show some error messages when an exception arise, I guess it's ok. But if you find the need to make some kind of processing depending on the type of exception, then you'll be better off try-catching in the inner code.
In your case it makes no sense since you do not process the exception you catch but simply print it. If you declare main throws checked_exceptions_your_code_throws_list you will get the same result (JVM will print exception) and a cleaner code. And if your code throws no checked exception then do not declare any exceptions at all.

Difference between finally and write after catch

What is the difference between "finally" and write after "catch"?
For example:
public boolean example() {
try {
// Code
} catch (RuntimeException e) {
// Code
} finally {
return true;
}
}
public boolean example() {
try {
// Code
} catch (RuntimeException e) {
// Code
}
return true;
}
First of all, the only idiom that can even be considered a candidate is this:
try {
// stuff
} catch (Throwable t) {
// handle
}
// finally stuff
Note the caught type. Only if you catch any possible exception, including such dark monsters as ThreadDeath and VirtualMachineError can you hope to unconditionally reach the code below the try-catch.
But, that's only where it begins. What if the handling code itself throws an exception? So you need at least
try {
// main stuff
} catch (Throwable t) {
try {
// handle
} catch (Throwable t) {
// no code allowed here! Otherwise we descend into
// infinite recursion
}
}
// finally stuff
Now you may be beginning to realize the benefits of finally, but that's not all. Consider a quite typical scenario:
try {
// main stuff, may throw an exception. I want the exception to
// break what I'm doing here and propagate to the caller.
return true;
} finally {
// clean up, even if about to propagate the exception
}
How do you rewrite this? Without code duplication, impossible.
In the code you have provided there is no difference. But finally is used to run some piece of code after the try block no matter whether there is an exception or not.
Interesting point to make here is, we should avoid to return from the finally block because it can create confusion in scenarion when we return something from try block as well. Consider this piece of code:
try {
return true;
}
finally {
return false;
}
Now this code will return false no matter what happens in try. In many ways this behaviour is exactly consistent with the colloquial understanding of what finally means - "no matter what happens beforehand in the try block, always run this code." Hence if you return true from a finally block, the overall effect must always to be to return true, no?
In general, this is seldom a good idiom, and you should use finally
blocks liberally for cleaning up/closing resources but rarely if ever
return a value from them.
No difference in Your case. but
The runtime system always executes the statements within the finally block regardless of what happens within the try block.
So it's the perfect place to perform cleanup.
Note that if you're using JDK 7+, then most uses of the finally block can be eliminated, simply by using a try-with-resources statement.
We use try block, catch block and finally block to handle Exception in our program. A program may be have check or unchecked Exception. so this block are are used to handle those Exception. In the try block we mention or write those code which may be cause of an Exception and if we want that our code will be run if Exception occurred Then we write those code in the catch block. finally is a very special block which give us a special feature that if our catch block doesn't run then before the program goes to terminate that finally block code definitely execute. mostly this is use to save our data during unwanted program termination. if we use try block then there must be a catch block after the try block but finally is an optional not compulsory.
First thing to understand in this question is "why we use try{ } catch{ } block" Ok.
The answer is,when there is a possibility of our code of throwing an exception.
These kind of code we put in try{... } block &
catch {...} block contain the code to catch the exception generated by code in try{ } block.
Finally{...} block contain the code executed immediately after try{} catch{} block when try{ } block throws an exception.
e.g When you visit some website,but do to some server side problem it couldn't and page display some kind of message like "404 error or server is updating",these kind of code is written in finally block.
this simple catch only is for catch eXception and process it, but finally, execute if Exception or not , for example for close connections.
Finally block is useful to cleanup your code like closing open streams.
E.g:
File f = new File("\file.txt");
FileStream fs;
try{
fs = new FileStream(f);
} catch (IOException ioe){
ioe.printStackTrace();
} finally {
if (fs != null) {
fs.close() // close the stream
}
}
As your code only returning true/false , so it won't impact much . But think for any other code/logic where some mandatory/cleanup code is written to execute.
Also, it will difficult to catch all the exceptions via our code or in other words, we should catch specific exceptions which we can handle. At that point , finally will be real savior, as it will always execute(other than System.exit() or in some recursion case).
Also, for bringing the consistency in our code, one should always use finally block to perform any clean up code.
You may refer the below posts too for more clarification:
Using finally block vs writing code after the try/catch block
Try-catch-finally-return clarification
First Case:
If exception occurred in try block then catch block would be executed, and while serving the same catch block if there is again exception occurred then finally block would execute.
Second Case:
If exception occurred in try block then catch block would be executed, and if there is further exception in the same catch block then "return true;" would execute.
finally() is used whenever we want that some line of code should be executed even if exception occurs
But if u write line of code after catch it will not execute if exception occurs..

What is the difference between the following try-catch statements?

What is the difference between these usage of try-catch blocks and when you should use each one?
try {
doSomething1();
} catch(Exception e1){
exception_handle1();
}
try {
doSomething2();
} catch(Exception e2){
exception_handle2();
}
try {
doSomething1();
doSomething2();
} catch(Exception e1) {
exception_handle1();
} catch(Exception e2) {
exception_handle2();
}
try {
doSomething1();
try {
doSomething2();
} catch(Exception e2){
exception_handle2();
}
} catch(Exception e1){
exception_handle1();
}
try {
doSomthing1()
catch(Exception e1){
exception_handle1()
}
try {
doSomthing2()
catch(Exception e2){
exception_handle2()
}
doSomthing1() and doSomthing2() are unrelated methods. Failure of either one of them is independent on each other.
try {
doSomthing1()
doSomthing2()
catch(Exception e1){
exception_handle1()
}catch(Exception e2){
exception_handle2()
}
We can use the try-catch block this way to stop doSomthing2() method from executing if doSomthing1() fails. We can handle each exception individually with two catch blocks. But, one important point to note is that, your 2nd catch block is an unreachable code. In general, you should have catch block for more specific exceptions first, followed by generalized exception. Now, in your case, all the exception that 2nd catch block is supposed to handle will already be handled in the first one.
try {
doSomthing1()
try {
doSomthing2()
catch(Exception e2){
exception_handle2()
}
}
catch(Exception e1){
exception_handle1()
}
We have 2 try-catch blocks embedded in each other. Even after the doSomthing2() fails the program will continue inside the try block.
Well, the obvious difference between the first and the other two is that doSomthing2 will be attempted whether or not doSomthing1 threw an exception. In the exact code you quoted, there isn't a huge difference between the second and third examples (syntax errors aside) other than that in the third example, your exception handling code for the second try is within the exception handling code for the first, and so if it throws, the throw will be caught.
Which you should use depends entirely on the situation. Sometimes, it's appropriate to run doSomthing2 whether or not doSomthing1 throws an exception. Sometimes it isn't.
If doSomThing1 fails then the code moves on to execute doSomthing2
In the second example, doSomthing2 does not get executed if doSomthing1 fails
Whereas, third example is similar to second one.
First lets asume, doSomething1() and exceltion_handle1(), don't call System.exit(x) or something.
1) So first piece of code, will doSomething1(), no matter doSomething1() will throw any Exception or not, it will handle it (process the catch code block) and advance to second try and run it the same way.
try {
doSomething1();
} catch(Exception e1){
exception_handle1();
}
try {
doSomething2();
} catch(Exception e2){
exception_handle2();
}
It's morning, so I hope I won't make any wrong decisions.
2) This code will run doSomething1() then doSomething2(), and no matter which one will fail (throw Exception), only first catch clause will be called, as it absorbs all the subclasses and itself, so second catch won't be reached (first takes all the possible exceptions).
So afaik, you should get an error (shouldn't compile). It's smart and will recognize, that second catch won't be reached in any way.
The correct pattern would be : as we go to the bottom, exceptions should be broader and broader (strictly). It's logical, as order of catching clauses goes down, upper catch shouldn't be parent of bottom ones, as ANYWAY parent will take that exception, and childs in the bottom won't be reached.
Example: (I recommend you to learn about Multicatch in java.)
catch (Specific2ChildOfSpecific1 e3)
...
catch (specific1ChildOfException e2)
...
catch (Exception e1)
try {
doSomething1();
doSomething2();
} catch(Exception e1) {
exception_handle1();
} catch(Exception e2) {
exception_handle2();
}
3) This one: If doSomething1() will fail e1 catch clause will be executed and thats all, if it will pass, then if doSomething2() will run and if it fails, then e2 catch clause will be executed.
Notice # second example, no matter which doSomething will fail, e1 will be executed (don't forget there is an error as second is unreachable). But I understand what you wanted to ask.
try {
doSomething1();
try {
doSomething2();
} catch(Exception e2){
exception_handle2();
}
} catch(Exception e1){
exception_handle1();
}
its the same concept when you creating a conditionaL statement, just that conditionaL statement is testing the condition the try catch is testing an error

Categories

Resources