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..
Related
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 .
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.
I've got a doubt about using the try/catch/finally clauses,let me explain:
I know that every method which declares an exception specification in its declaration has to be surrounded (in a calling method) with a try block,followed by a catch block that can capture that exception (unless I don't declare the calling method throwing an exception as well). If the calling method has other statements after the try-catch, those are executed regardless of what happens (exception thrown or not). So if I have the following code:
public class ExceptionCall {
Throwing t = new Throwing();
public void methodTry(){
while(true){
try {
if (t.flag++==0)
t.throwing();
System.out.println("no exception");
}
catch (MyException e) {
e.printStackTrace(System.err);
System.out.println("working on it!");
}
finally{
System.out.println("finally clause");
}
System.out.println("out");
if (t.flag==2)
break;
}
}
}
Here Throwing has a method called (guess what :) ) throwing() which is declared to throw a MyException exception, and has a public field called flag containing an int initialized to 0 to provide a sort of condition checking.
So for a couple of times the code outside the guarded region is executed no matter what happens in the try block.
So my question is, what is the finally block for?? I mean, I know it comes in handy when the calling method returns from the try or the catch block (in this case I could have a break statement inside the catch and the finally would be executed), but in a case like this what's the difference??
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
See : https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
Finally block is used to handle those resources that need you to make some action at the end of the statement no matter what happens in the code.
For example: readers or streams are resources that must be closed after it's use, but exceptions can happen during it's usage, so where you close them???
Here is where finally clause becomes really handy:
FileReader reader;
try {
reader = new FileReader("someNonExistingFile");
} catch (FileNotFoundException e) {
// handle FileNotFoundException
e.printMessage();
} finally {
// reader MUST BE CLOSED ALWAYS, so FINALLY, CLOSE IT
reader.close();
}
In this example, you need to close reader always (if file exists and if file doesn't) so, instead of closing it twice (in try and in catch) you use finally.
Further info and examples of finally here. Also check try with resources (Java 7+).
This question already has answers here:
Does a finally block always get executed in Java?
(51 answers)
Closed 9 years ago.
I have this java code with nested try:
try
{
try
{
[ ... ]
{
catch (Exception ex)
{
showLogMessage(ex);
return;
}
while (condition == true)
{
try
{
[ ... ]
{
catch (Exception ex)
{
showLogMessage(ex);
continue;
}
[ ... ]
}
}
catch (NumberFormatException e)
{
showLogMessage(e);
}
finally
{
doSomeThingVeryImportant();
}
I want to know if finally is always executed when I get an exception. I ask this because catch blocks have return or continue statements.
When is doSomeThingVeryImportant() executed? When I get an Exception on when I get a NumberFormatException?
I only want if after any catch block is executed, the finally block is executed also.
The finally block, if used, is placed after a try block and the catch blocks that follow it. The finally block contains code that will be run whether or not an exception is thrown in a try block. The general syntax looks like this:
public void someMethod{
Try {
// some code
}
Catch(Exception x) {
// some code
}
Catch(ExceptionClass y) {
// some code
}
Finally{
//this code will be executed whether or not an exception
//is thrown or caught
}
}
There are 4 potential scenarios here:
The try block runs to the end, and no exception is
thrown. In this scenario, the finally block will be
executed after the try block.
An exception is thrown in the try block, which is
then caught in one of the catch blocks. In this scenario,
the finally block will execute right after the catch block
executes.
An exception is thrown in the try block and there's
no matching catch block in the method that can catch
the exception. In this scenario, the call to the method
ends, and the exception object is thrown to the enclosing
method - as in the method in which the try-catch-finally
blocks reside. But, before the method ends, the finally
block is executed.
Before the try block runs to completion it returns to
wherever the method was invoked. But, before it returns
to the invoking method, the code in the finally block is still
executed. So, remember that the code in the finally block
willstill be executed even if there is a return
statement somewhere in the try block.
Update: Finally ALWAYS gets executed, no matter what happens in the try or catch block (fail, return, exception, finish etc.).
The finally block always executes when the try block exits (click).
Yes, Finally always executes. With exception and with NO exception.
It's the way to be sure some portion of code get always executed.
Used for example, to dispose objects, to close opened server connections and that kind of stuff.
Check this link from oracle:
http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
Yes, finally blocks are always executed.
Source: http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
Yes; or, at least, as close to "always" as possible. (So, even if you have a return or another throw.)
If your process is killed, or your program gets stuck in a deadlock or infinite loop, or your device is struck by a meteor, then program flow will not reach the finally block.
Say your code block is something like this :
try
{
try
{
System.out.println("first try block");
}
catch (Exception ex)
{
System.out.println("first cathc block");
return;
}
while (true)
{
try
{
System.out.println("second try block...");
}
catch (Exception ex)
{
System.out.println("second catch block");
continue;
}
System.out.println("end of loop");
break;
}
}
catch (NumberFormatException e)
{
System.out.println("last catch block");
}
finally
{
System.out.println("finally block");
}
If you run this then the output that you will get is :
first try block
second try block...
end of loop
finally block
So finally block gets executed anyway.
The finally block always executes when the try block exits.
This ensures that the finally block is executed even if an unexpected exception occurs
Taken from here: http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
Further, the page explains that the finally block may not be executed if the JVM exists while the try or catch code is being executed, or if the thread executing the try/catch is interrupted or killed.
So unless you may kill the JVM or the try/catch is beeing executed in a thread, the finally block will always be executed
Yes, finally blocks are always executed. But terms and conditions apply .
Untill unless you call System.exit();
Yes finally always gets executed and its because one can program to close/handle resources in case of exceptions or no exception without fail.
http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
Update to answer the question in comment about System.exit()
The finally block will not execute in case of System.exit() unless it fails with some SecurityException.
Update after question changed. No matter what the exception is finally block will always execute.
If its Exception then your catch block will not execute as it catches only NumberFormatException
No, finally won't get execute always. There are two situations where Finally won't get execute.
Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
java reference
For your question, if these two things are not there, whatever inside your finally will get executed, that's sure.
This question already has answers here:
Why use finally
(9 answers)
Closed 1 year ago.
As far as I can tell, both of the following code snippets will serve the same purpose. Why have finally blocks at all?
Code A:
try { /* Some code */ }
catch { /* Exception handling code */ }
finally { /* Cleanup code */ }
Code B:
try { /* Some code */ }
catch { /* Exception handling code */ }
// Cleanup code
What happens if an exception you're not handling gets thrown? (I hope you're not catching Throwable...)
What happens if you return from inside the try block?
What happens if the catch block throws an exception?
A finally block makes sure that however you exit that block (modulo a few ways of aborting the whole process explicitly), it will get executed. That's important for deterministic cleanup of resources.
Note that (in Java at least, probably also in C#) it's also possible to have a try block without a catch, but with a finally. When an exception happens in the try block, the code in the finally block is run before the exception is thrown higher up:
InputStream in = new FileInputStream("somefile.xyz");
try {
somethingThatMightThrowAnException();
}
finally {
// cleanup here
in.close();
}
You may want to put the code that you want to anyway get executed irrespective of what happens in your try or catch block.
Also if you are using multiple catch and if you want to put some code which is common for all the catch blocks this would be a place to put- but you cannot be sure that the entire code in try has been executed.
For example:
conn c1 = new connection();
try {
c1.dosomething();
} catch (ExceptionA exa) {
handleexA();
//c1.close();
} catch (ExceptionB exb) {
handleexB();
//c1.close();
} finally {
c1.close();
}
Finally always gets executed, where as your code after the catch may not.
Even though our application is closed forcefully there will be some tasks, which we must execute (like memory release, closing database, release lock, etc), if you write these lines of code in the finally block it will execute whether an exception is thrown or not...
Your application may be a collection of threads, Exception terminates the thread but not the whole application, in this case finally is more useful.
In some cases finally won't execute such as JVM Fail, Thread terminate, etc.
Still scrolling down? Here you go!
This question gave me tough time back a while.
try
{
int a=1;
int b=0;
int c=a/b;
}
catch(Exception ex)
{
console.writeline(ex.Message);
}
finally
{
console.writeline("Finally block");
}
console.writeline("After finally");
what would be printed in the above scenario?
Yes guessed it right:
ex.Message--whatever it is (probably attempted division by zero)
Finally block
After finally
try
{
int a=1;
int b=0;
int c=a/b;
}
catch(Exception ex)
{
throw(ex);
}
finally
{
console.writeline("Finally block");
}
console.writeline("After finally");
What would this print? Nothing! It throws an error since the catch block raised an error.
In a good programming structure, your exceptions would be funneled, in the sense that this code will be handled from another layer. To stimulate such a case i'll nested try this code.
try
{
try
{
int a=1;
int b=0;
int c=a/b;
}
catch(Exception ex)
{
throw(ex);
}
finally
{
console.writeline("Finally block")
}
console.writeline("After finally");
}
catch(Exception ex)
{
console.writeline(ex.Message);
}
In this case the output would be:
Finally block
ex.Message--whatever it is.
It is clear that when you catch an exception and throw it again into other layers(Funneling), the code after throw does not get executed. It acts similar to just how a return inside a function works.
You now know why not to close your resources on codes after the catch block.Place them in finally block.
Because you need that code to execute regardless of any exceptions that may be thrown. For example, you may need to clean up some unmanaged resource (the 'using' construct compiles to a try/finally block).
There may be times when you want to execute a piece of code no matter what. Whether an exception is thrown or not. Then one uses finally.
finally ALWAYS executes, unless the JVM was shut down, finally just provides a method to put the cleanup code in one place.
It would be too tedious if you had to put the clean up code in each of the catch blocks.
If catch block throws any exception then remaining code will not executed hence we have to write finaly block.
finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc.
The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).