Today at work, I had to review a code snippet that looks similar to this mock example.
package test;
import java.io.IOException;
import org.apache.log4j.Logger;
public class ExceptionTester {
public static Logger logger = Logger.getLogger(ExceptionTester.class);
public void test() throws IOException {
new IOException();
}
public static void main(String[] args) {
ExceptionTester comparator = new ExceptionTester();
try {
try {
comparator.test();
} finally {
System.out.println("Finally 1");
}
} catch(IOException ex) {
logger.error("Exception happened" ex);
// also close opened resources
}
System.out.println("Exiting out of the program");
}
}
It's printing the following output.I expected an compile error since the inner try did not have a catch block.
Finally 1
Exiting out of the program
I do not understand why IOException is caught by the outer catch block. I would appreciate if anyone can explain this, especially by citing stack unwinding process
A finally block represents a task that has to be done under both normal and abnormal conditions.
Example: You take an interview candidate to lunch. While at lunch, you find out he's wanted by the police for murder. Exception! Lunch is over, the interview is a total loss, but... you still have to pay for lunch.
try {
meetForLunch(interviewCandidate);
}
finally {
lunchBill.pay();
}
Note that paying for lunch hasn't taken care of the exception, you've still got to do something about the murderer at your interview. It's just a loose end that has to be taken care of before processing with damage control.
Most finally blocks are used in that way: A file needs to be closed whether you successfully saved the data or not, a database connection needs to be closed whether the transaction was approved or not, etc.
And the exception continues outward on its merry way, looking for a matching catch block in an enclosing scope.
Note that finally blocks will always run unless the process ends while the try block is still executing.
I think the problem is that your function
public void test() throws IOException {
new IOException();
}
Doesn't actually throw an exception - it just creates a new IOException() object. Changing this to
public void test() throws IOException {
throw new IOException();
}
should fix this.
The code above does not require much of an explanation - not definitely involving call stacks!. What is your confusion?did I miss something?
Here is my explanation
First point
You don't need both a catch and a
finally block. You can have one of
them or both of them with a
try-block, but not none of them.
The code inside the finally clause
will always be executed, even if an
exception is thrown from within the
try or catch block. If your code has
a return statement inside the try or
catch block, the code inside the
finally-block will get executed
before returning from the method.
So in the above code, an exception was never thrown (because you are not using throw in the test() method)
However, finally block got executed as promised by the the language spec and you got the output Finally 1. The next statement in the sequence of execution is the System.out.println("Exiting out of the program"); as the catch block never reached as there are no IOExceptions. So, Exiting out of the program is printed.
Related
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+).
I am fairly new to using try/catch blocks, so I don't know how exactly to perform this command.
If I catch an error, I would like to wait a period of time(10 seconds or so) then try to run the same line of code to attempt to continue in my try block. My program is written in Java. I have looked at both these pages: Page1, Page2, but neither of them are in Java. I have also looked at this, but they are not solving in the using the catch block. Is this possible to do, and how would I implement this in my catch block instead of just printing the error?
99% of time, you want to re-run a code-block after a try-catch and not the line with exception.
If you need to run from that line, than that is an indication for you to take your code in another method that encapsulates only that code (maybe move the try-catch there too).
What i would advice is something like this:
void method(){
try{
codeline1;
codeline2;
codeline3;
codeline4;
}
catch(Exception ex)
{
restorClassStateBeforeCodeLine1();
method();
}
}
By that snipped i propose to have your entire try-catch in a separate method.
Waiting random intervals is bad practice also. You never know if 10 seconds is right every time or at all.
Another way that I advise against would be:
label: {
try {
...
if (condition)
break label;
...
} catch (Exception e) {
...
}
}
It uses java labels to retry that part. I never tried but the break could be moved in the catch and the label in the try.
I don't think it is possible to return to a certain line in your try-block from inside a catch-block. Because when the throwis executed, the runtime system is going to pop frames from the call stack, looking for an exception handler to match the thrown exception and once the frame is popped from the stack, it's gone. More info about this can be found here
What you can do is call the method that caused the throw from within the catch-block. But that means it is going to execute your method from the beginning, so maybe you want to try to rearrange your code so that this does not cause any other problems. EDIT: The other answer demonstrates exactly what I mean.
This simple program loops through array values, testing each until it finds a value that doesn't generate an exception
public static void main(String[] args) {
int[] array=new int[]{0,0,0,0,5};
for(int i=0; i<array.length;i++) {
try {
System.out.println(10/array[i]);
break;
} catch(Exception e) {
try { Thread.sleep(1000); } catch(Exception ignore){}
}
}
}
while(true){
try{
//actions where some exception can be thrown
break;//executed when no exceptions appeared only
}
catch(YourException e){
Thread.sleep(10_000);
}
}
This cycle will be repeated while you instructions haven't executed. When code in try-block executed succesfully break helps you leave this cycle
Since you are saying that it is only 2 lines of code that you experience the intermittent error with, try something similar to this.
public static void main(String... args)
{
try
{
//Some Logic
//Error throwing logic in method
while(!doLogic())
{
Thread.sleep(1000);//Sleep here or in doLogic catch
}
//Continuing other logic!
}
catch(Exception e)
{
e.printStackTrace();
}
}
static Integer i = null;
public static boolean doLogic()
{
try
{
//Lines that throw error
System.out.println(i.toString());//NPE First run
}
catch (Exception e)
{
i = 1;
return false;
}
return true;
}
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..
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).