You really need a finally block

There are 3 permutations of try ... catch ... finally block in java.

  • Try ... Catch
  • try ... catch ... finally
  • try ... finally

Once the finally block is executed, control proceeds to the next line after the finally block. If I delete the finally block and move all its statements to the line after the try ... catch block, will it have the same effect as them in the finally block?

+46
java exception-handling
05 Oct 2018-10-10T00:
source share
9 answers

I think the willcode code will be closest to the key point expression here, and it probably all means, but not clear.

The problem is that there is something very wrong with what you ask: "If I write all the instructions after the catch block instead of writing them to the finally block, then will there be something wrong?"

If you write all the instructions after the catch block, then you mean that

1) You will always catch an exception.

2) After you catch the exception, you will always continue with the following instructions.

This means that you will always continue to execute "normally" after the exception, which usually means that you really never .

Exceptions should be just that - exceptional. If you can really handle the exception, it is always best to write your own code to consider these conditions first and not lead to an exception at all. If you follow this model, the exceptions are really exceptional - conditions that you could not foresee or, at most, cannot be corrected. Do not really expect that you should work. This means that in general you cannot handle true exceptions, which also means that you should not just continue execution, often you end the application.

What is usually done, you allow the error to distribute a backup of the call stack. Some say that this is done in case someone higher up in the chain can handle it. I would say that essentially never happens, there are two real goals for this. One of them may be something that the user can fix if he is. This way you spread the error until you get to where you can report it to the user. Or two, the user cannot fix this, but you want to get the whole call stack for debugging. Then you catch him upstairs to fail gracefully.

The finally block should now have more meaning to you. As everyone says, it always works. The clearest use is finally really in an attempt ... to finally block. Now you say that the code works fine, fine. We still need to clean up a bit, and finally, we always execute and then continue. But if some kind of exception occurs, we really need this block to be finally blocked, because we still need to clear a bit, but we no longer catch the exceptions here, so we will no longer move on. The finally block is needed to provide cleanup.

The idea of ​​an exception that always stops execution can be difficult for someone until they have a certain experience, but in fact it is a way to always do something. If an error occurred, or it was so insignificant that you had to take it into account, or simply more and more errors awaiting what would happen along the line.

The "swallowing" errors - catching them and moving on - this is the worst thing you can do, because your program becomes unpredictable and you cannot find and fix errors.

Well-written code will contain as many attempts ... finally blocks as necessary to ensure that resources will always be released regardless of the result. But well-written code usually contains only a small number of try ... catch blocks, which exist primarily so that the application can fail as gracefully as possible, or put off to the user, which means at least always send a message user etc. But you usually do not just catch the mistake and keep going.

+40
05 Oct 2018-10-10T00:
source share

It is guaranteed that the finally block will be executed even if an exception occurs. You use them to perform the necessary cleaning, for example, to close threads. Code after the finally block will never be reached.

From java tutorial

The finally block is always executed when the try block is turned off. This ensures that the finally block is executed even if an unexpected exception is thrown. But finally, it is useful not only for exception handling - it allows the programmer to avoid cleaning up code that accidentally manages to return, continue or break. Entering the cleanup code in the finally block is always good practice, even when no exceptions are expected.

+37
Oct 05 '10 at 7:15
source share

I know this is a very old question, but I came across today, and I was confused by the answers. I mean that they are all correct, but they all answer at a theoretical or even philosophical level, when there is a very simple practical answer to this question.

If you put a return, break, continuation, or any other java keyword that changes the sequential execution of the code inside the catch block, the statements inside the finally block will still be executed.

For example:

public void myFunc() { double p = 1.0D; String str = "bla"; try{ p = Double.valueOf(str); } catch(Exception ex){ System.out.println("Exception Happened"); return; //return statement here!!! }finally{ System.out.println("Finally"); } System.out.println("After finally"); } 

when this code is executed, it will print:

 Exception Happened Finally 

This is the most important reason for the existence of the finally block. Most answers imply this or refer to it aside, but none of them focus on this. I think, because this is a kind of question for beginners, such a simple answer is very important.

+27
May 8 '14 at 9:02
source share

If I understand the question, you are asking what is the difference between:

 try { Foo f = new Foo(); f.bar(); } finally { Foo.baz(); } 

and

 // This doesn't actually compile because a try block needs a catch and/or finally block try { Foo f = new Foo(); f.bar(); } Foo.baz(); 

Or, more likely:

 Foo f = new Foo(); f.bar(); Foo.baz(); 

The difference is that if either new Foo() or f.bar() exception, the finally block will be executed in the first case, but Foo.baz() will not be executed in the last two cases: instead, the control will skip Foo.baz() , while the JVM is looking for an exception handler.




EDIT

Responding to your comment, how about:

 Foo f = new Foo(); try { f.bar(); } catch (Exception ex) { // ... } f.baz(); 

You are right to assume that the catch does not reconstruct the exception or does not return a method that indicates a failure, then f.baz() is called regardless of whether the exception was thrown. However, even in this case, the finally block serves as documentation that f.baz() used to clean up.

More importantly, the fact that an exception is thrown is usually very important, so it’s very difficult to write code that continues to do what it does without knowing that the exception was thrown. There are times when exceptions show stupid things that you can ignore, in which case you must catch the exception. Most often, however, you will want to signal a failure, either by rebuilding the exception (or throwing another exception) or returning from the method with the error code.

For example, if f.bar() supposed to convert a String to Double , and if it NumberFormatException , it throws a NumberFormatException , then the code after the try block should probably know that String is not actually converted to Double . And thus, in the general case, you will not want to continue working after the catch . Instead, you will want to signal a failure. This is called a “fail interruption” (compared to “resuming failure,” which should probably be called “crossing fingers after failure”).

In addition, in special cases you may get confused. For example, a catch can set the corresponding Double to Double.NaN , which is specifically designed to correctly propagate errors in mathematical expressions. Even so, the finally block serves as documentation in which f.baz() involved in some kind of cleanup.

+10
Oct 05 2018-10-10T00:
source share

The finally block contains lines of code that should be executed regardless of whether an exception has been detected. Even if you decide to stop code execution in this method. Thus, the code after tcf may not be executed, but the finally code is "guaranteed" (guaranteed in the sense that it does not fail, immediately violating the error without processing).

+3
Oct 05 '10 at 7:16
source share

Yes, it would be very critically wrong.

In other words, your code will only work if there is an error.

Statements inside finally always run regardless of the exception thrown. That is the point.

+2
05 Oct '10 at 7:14
source share

permanently blocked, especially used during exception prevention. If any error occurs at runtime, the program may lead to termination. Thus, at this time it will call the final block before closing the program. Usually, "finally" contains instructions for closing the connection, operations for saving and entering files, and output for closing operations.

+1
Oct 05 '10 at 7:27
source share

If your code never throws an exception, or you consume all exceptions, this will be correct. This is not what always happens.

+1
Oct 05 '10 at 7:55
source share

Two months ago, I wrote a message for the reason "finally" in try / catch.

Knowing that the link to the wiki-style editing path is here.

This is a standalone post that just copies it will not work as you miss a comment that will also add value.

0
Oct 05 '10 at 8:22
source share



All Articles