I am trying to put a while loop inside a try /catch block. To my curiosity finally of that try catch is not executed when the while loop exits. Can some explain what is happening actually?
I tried to google, but cnould not find any details.
I assume your code looks like this:
try
{
while (...)
{
// ...
}
}
catch (FooException ex)
{
// This only executes if a FooException is thrown.
}
finally
{
// This executes whether or not there is an exception.
}
The catch block is only executed if there is an exception. The finally block usually executes whether or not an exception was thrown. So you will probably find that your finally block is actually being executed. You can prove this to yourself by placing a line there that causes some output to the console.
However there are situations in which the finally block doesn't run. See here for more details:
Does a finally block always run?
It can happen only if your program exits either by using System.exit() or if an Error or Throwable were thrown (vs. Exception that will be caught).
Try the following:
public static void main(String[] args) {
try{
System.out.println("START!");
int i=0;
while(true){
i++;
if(i > 10){
System.exit(1);
}
}
}
catch (Exception e) {
// TODO: handle exception
}
finally{
System.out.println("this will not be printed!");
}
}
Related
I have the following function that read data from file.
If i get an IO exception, I want to finish the run of this function and continue to next functions in this program.
what should i add to the code?
I tried to add continue to the finnally block but I get error "continue cannot be used outside of a loop".
public void readFromFile() throws Exception
{
BufferedReader f= new BufferedReader(new FileReader("C:\\T.DAT"));
String l="";
try{
do{
l = f.readLine();
if(l != null)
{
Car a = new Car();
a.setFromLine(l);
alCars.add(a);
}
} while(line !=null);
}
catch (Exception e)
{
System.out.println("can't open file IO ERROR. program is continueing");
}
finally
{
f.close();
}
}
simply put return; in the finally block
You cannot use continue outside the loop.
Catch and finally is outside the loop.
Insert try - catch - finally into the do while clause and it would work.
If you use catch block you don't have to use throws after method signature.
Simply catch Exception in catch block, and in finally do something.
Do first catch for IOException and in all other cases do another catch for Exception.
try {
//
}
catch ( IOException e ) {
System.out.println("IO Exception occured");
}
catch ( Exception e ) {
//other exceptions
}
finally {
//deinitialize
}
I am not sure if ioexception occurs, then in finally you have to close file. maybe it's null object
You don't have to do anything. The code will return from the function after the finally block has been executed.
I have a project having Exception handling written in the following way:
Parent class has all the exception handling logic. And the invoked class just throws exception and the invoker class handles with appropriate logic.
Now the problem that I am facing invoked class opens different stuffs for example, a file. These files are not getting closed at the time of exception.
so what should be the appropriate way of exception handling in this case.
class A
{
private void createAdminClient()
{
try
{
B b = new B();
b.getClinetHandler();
}
catch(CustomException1 e1)
{
}
catch(CustomException2 e1)
{
}
catch(CustomException3 e1)
{
}
catch(CustomException4 e1)
{
}
}
}
class B
{
................
................
getClinetHandler() throws Exception
{
--------------------------
---- open a file----------
--------------------------
----lines of code---------
--------------------------
Exceptions can happen in these lines of code.
And closing file may not be called
--------------------------
---- close those files----
--------------------------
}
}
You can wrap the code which may throw an exception in a try...finally block:
getClientHandler() throws Exception {
// Declare things which need to be closed here, setting them to null
try {
// Open things and do stuff which may throw exception
} finally {
// If the closable things aren't null close them
}
}
This way the exception still bubbles up to the exception handler but the finally block ensures that the closing code still gets called in the event of an exception.
use a finally block to complete the final tasks. for example
try
{
B b = new B();
b.getClinetHandler();
}
catch(CustomException1 e1)
{
}
finally{
// close files
}
From the doc
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.
This is how I do it
try {
//What to try
} catch (Exception e){
//Catch it
} finally {
//Do finally after you catch exception
try {
writer.close(); //<--Close file
} catch (Exception EX3) {}
}
Use a finally block to handle post-processing execution (regardless whether it succeeded or failed). Like so:
// Note: as Sean pointed out, the b variable is not visible to the finally if it
// is declared within the try block, therefore it will be set up before we enter
// the block.
B b = null;
try {
b = new B();
b.getClinetHandler();
}
catch(CustomException1 e1) {
} // and other catch blocks as necessary...
finally{
if(b != null)
b.closeFiles() // close files here
}
The finally block is always executed, regardless, even if you throw or return from the try or catch blocks.
This answer provides a very good explanation of how the finally block works in this situation, and when/how it is executed, and basically further illustrates what I just wrote.
class chain_exceptions{
public static void main(String args[]){
try
{
f1();
}
catch(IndexOutOfBoundsException e)
{
System.out.println("A");
throw new NullPointerException(); //Line 0
}
catch(NullPointerException e) //Line 1
{
System.out.println("B");
return;
}
catch (Exception e)
{
System.out.println("C");
}
finally
{
System.out.println("D");
}
System.out.println("E");
}
static void f1(){
System.out.println("Start...");
throw new IndexOutOfBoundsException( "parameter" );
}
}
I expected the Line 1 to catch the NullPointerException thrown from the Line 0 but it does not happen.
But why so ?.
When there is another catch block defined, why cant the NPE handler at Line1 catch it ?
Is it because the "throw" goes directly to the main() method ?
Catch{ . . . } blocks are associated with try{ . . . } blocks. A catch block can catch exceptions that are thrown from a try block only. The other catch blocks after first catch block are not associated with a try block and hence when you throw an exception, they are not caught. Or main() does not catch exceptions.
A kind of this for each catch block will do what you are trying to do.
try{
try
{
f1();
}
catch(IndexOutOfBoundsException e)
{
System.out.println("A");
throw new NullPointerException(); //Line 0
}
}
catch(NullPointerException e) //Line 1
{
System.out.println("B");
return;
}
The catch blocks are only for the try block. They won't catch exceptions from other catch blocks.
catch statements only catch exceptions thrown from a try { ... } block.
The NullPointerException is thrown from a catch { ... } block, not a try { ... } block.
To catch an exception thrown from a catch block you need to put another try block inside of it. Outside, wrapping the original try...catch would work, too.
A second catch doesn't catch the exception from the first catch block. You have to add another try-catch within the first catch block (or around the whole try-catch you already have) to make this run as expected.
Since java 7 you can use code below or an other option is to nest the try catch statements, there is no other option in java
try {
...
} catch( indexoutofboundsexception| nullpointerexception ex ) {
logger.log(ex);
throw ex;
}
Your catch clauses only catch exceptions thrown by f1(). They don't call exceptions thrown in other catch clauses of the same try-catch-finally construct.
Because f1() throws IndexOutOfBoundsException.
try
{
f1(); //throws IndexOutOfBoundsException
}
catch(IndexOutOfBoundsException e) //gets caught here immediately and does not check other catch blocks
{
System.out.println("A");
throw new NullPointerException(); //Line 0
}
Short answer: yes, the throw will directly throw the exception to the main method.
Generally, once a catch block is executed, it behaves like an else if, that is, it won't consider the other alternatives.
No, the reason it isn't being caught is because it isn't in the try block which is linked to the catch block. If you want to catch that exception as well, you would have to wrap the throw in a new try/catch group. The reason why you would want to do this tho, is a riddle to me.
What you also can do btw:
catch (IndexOutOfBoundsException|NullPointerException e)
This will also allow you to use the same catch block for multiple types of exceptions.
Your expectation was incorrect:
The catch blocks are associated with the try block. So once an exception is thrown inside of the try, it leaves that scope. Now you are in the scope outside the try, meaning you are no longer in any try/catch block. Any exceptions thrown here (when you re-throw) will not be caught by anything, and yes, bubble out of main.
You can not catch exception from another catch block, for that you probably need to do something like this, in your first catch block
System.out.println("A");
try{
throw new NullPointerException(); //Line 0
}
catch(NullPointerException e) //Line 1
{
System.out.println("B");
return;
}
I have wrote the code below which was taken from Java How to program 9th Edition - Paul and Michelle Harvey - The code works fine but the problem is that every time I execute it, it gives me uncertain results in which the exceptions are handled - e.g. please look at the output of the code snippet. can you please help me understand why this behavior is occurring ?
public class Test {
public static void main(String[] args) {
try {
// call method throwException
throwException();
}// end try
catch (Exception e) {
System.out.println("Exception handled in main");
}// end catch
// call method doesNotThrowException
doesNotThrowException();
}
private static void throwException() throws Exception {
try {
System.out.println("Method throwException.");
throw new Exception(); // generate exception
}
catch (Exception exception) {
System.err.println("Exception handled in method throwException");
throw exception;
}
// executes regardless of what occurs in try ... catch block
finally {
System.err.println("Finally executed in throwException.");
}
}// end of method throwException
private static void doesNotThrowException() {
try {
System.out.println("Method doesNotThrowException.");
}
// catch does not execute as the method does not throw any exceptions
catch (Exception exception) {
System.err.println(exception);
}// end catch
// executes regardless of what occurs in try ... catch block
finally {
System.err.println("Finally executed in doesNotThrowException");
}
}// end of deosNotThrowException
}//end Test Class
OUTPUTS:
1)
Method throwException.
Exception handled in method throwException
Finally executed in throwException.
Finally executed in doesNotThrowException
Exception handled in main
Method doesNotThrowException.
2)
Exception handled in method throwException
Finally executed in throwException.Method throwException.
Finally executed in doesNotThrowException
Exception handled in main
Method doesNotThrowException.
Different outputs on different runs are because of you're using 2 different output streams: out and err. It's up to the OS to flush such I/O streams and it does so in different ways on each run depending on other factors that have nothing to do with your program. The only thing the OS guarantees is that the order for out and the order for err are preserved, but not the order between them.
On a question for Java at the university, there was this snippet of code:
class MyExc1 extends Exception {}
class MyExc2 extends Exception {}
class MyExc3 extends MyExc2 {}
public class C1 {
public static void main(String[] args) throws Exception {
try {
System.out.print(1);
q();
}
catch (Exception i) {
throw new MyExc2();
}
finally {
System.out.print(2);
throw new MyExc1();
}
}
static void q() throws Exception {
try {
throw new MyExc1();
}
catch (Exception y) {
}
finally {
System.out.print(3);
throw new Exception();
}
}
}
I was asked to give its output. I answered 13Exception in thread main MyExc2, but the correct answer is 132Exception in thread main MyExc1. Why is it that? I just can't understand where does MyExc2 go.
Based on reading your answer and seeing how you likely came up with it, I believe you think an "exception-in-progress" has "precedence". Keep in mind:
When an new exception is thrown in a catch block or finally block that will propagate out of that block, then the current exception will be aborted (and forgotten) as the new exception is propagated outward. The new exception starts unwinding up the stack just like any other exception, aborting out of the current block (the catch or finally block) and subject to any applicable catch or finally blocks along the way.
Note that applicable catch or finally blocks includes:
When a new exception is thrown in a catch block, the new exception is still subject to that catch's finally block, if any.
Now retrace the execution remembering that, whenever you hit throw, you should abort tracing the current exception and start tracing the new exception.
Exceptions in the finally block supersede exceptions in the catch block.
Java Language Specification
If the catch block completes abruptly for reason R, then the finally
block is executed. Then there is a choice:
If the finally block completes normally, then the try statement completes abruptly for reason R.
If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).
This is what Wikipedia says about finally clause:
More common is a related clause
(finally, or ensure) that is executed
whether an exception occurred or not,
typically to release resources
acquired within the body of the
exception-handling block.
Let's dissect your program.
try {
System.out.print(1);
q();
}
So, 1 will be output into the screen, then q() is called. In q(), an exception is thrown. The exception is then caught by Exception y but it does nothing. A finally clause is then executed (it has to), so, 3 will be printed to screen. Because (in method q() there's an exception thrown in the finally clause, also q() method passes the exception to the parent stack (by the throws Exception in the method declaration) new Exception() will be thrown and caught by catch ( Exception i ), MyExc2 exception will be thrown (for now add it to the exception stack), but a finally in the main block will be executed first.
So in,
catch ( Exception i ) {
throw( new MyExc2() );
}
finally {
System.out.print(2);
throw( new MyExc1() );
}
A finally clause is called...(remember, we've just caught Exception i and thrown MyExc2) in essence, 2 is printed on screen...and after the 2 is printed on screen, a MyExc1 exception is thrown. MyExc1 is handled by the public static void main(...) method.
Output:
"132Exception in thread main MyExc1"
Lecturer is correct! :-)
In essence, if you have a finally in a try/catch clause, a finally will be executed (after catching the exception before throwing the caught exception out)
Finally clause is executed even when exception is thrown from anywhere in try/catch block.
Because it's the last to be executed in the main and it throws an exception, that's the exception that the callers see.
Hence the importance of making sure that the finally clause does not throw anything, because it can swallow exceptions from the try block.
A method can't throw two exceptions at the same time. It will always throw the last thrown exception, which in this case it will be always the one from the finally block.
When the first exception from method q() is thrown, it will catch'ed and then swallowed by the finally block thrown exception.
q() -> thrown new Exception -> main catch Exception -> throw new Exception -> finally throw a new exception (and the one from the catch is "lost")
class MyExc1 extends Exception {}
class MyExc2 extends Exception {}
class MyExc3 extends MyExc2 {}
public class C1 {
public static void main(String[] args) throws Exception {
try {
System.out.print("TryA L1\n");
q();
System.out.print("TryB L1\n");
}
catch (Exception i) {
System.out.print("Catch L1\n");
}
finally {
System.out.print("Finally L1\n");
throw new MyExc1();
}
}
static void q() throws Exception {
try {
System.out.print("TryA L2\n");
q2();
System.out.print("TryB L2\n");
}
catch (Exception y) {
System.out.print("Catch L2\n");
throw new MyExc2();
}
finally {
System.out.print("Finally L2\n");
throw new Exception();
}
}
static void q2() throws Exception {
throw new MyExc1();
}
}
Order:
TryA L1
TryA L2
Catch L2
Finally L2
Catch L1
Finally L1
Exception in thread "main" MyExc1 at C1.main(C1.java:30)
https://www.compilejava.net/
The logic is clear till finish printing out 13. Then the exception thrown in q() is caught by catch (Exception i) in main() and a new MyEx2() is ready to be thrown. However, before throwing the exception, the finally block have to be executed first. Then the output becomes 132 and finally asks to thrown another exception new MyEx1().
As a method cannot throw more than one Exception, it will always throw the latest Exception. In other words, if both catch and finally blocks try to throw Exception, then the Exception in catch is swallowed and only the exception in finally will be thrown.
Thus, in this program, Exception MyEx2 is swallowed and MyEx1 is thrown. This Exception is thrown out of main() and no longer caught, thus JVM stops and the final output is 132Exception in thread main MyExc1.
In essence, if you have a finally in a try/catch clause, a finally will be executed AFTER catching the exception, but BEFORE throwing any caught exception, and ONLY the lastest exception would be thrown in the end.
The easiest way to think of this is imagine that there is a variable global to the entire application that is holding the current exception.
Exception currentException = null;
As each exception is thrown, "currentException" is set to that exception. When the application ends, if currentException is != null, then the runtime reports the error.
Also, the finally blocks always run before the method exits. You could then requite the code snippet to:
public class C1 {
public static void main(String [] argv) throws Exception {
try {
System.out.print(1);
q();
}
catch ( Exception i ) {
// <-- currentException = Exception, as thrown by q()'s finally block
throw( new MyExc2() ); // <-- currentException = MyExc2
}
finally {
// <-- currentException = MyExc2, thrown from main()'s catch block
System.out.print(2);
throw( new MyExc1() ); // <-- currentException = MyExc1
}
} // <-- At application exit, currentException = MyExc1, from main()'s finally block. Java now dumps that to the console.
static void q() throws Exception {
try {
throw( new MyExc1() ); // <-- currentException = MyExc1
}
catch( Exception y ) {
// <-- currentException = null, because the exception is caught and not rethrown
}
finally {
System.out.print(3);
throw( new Exception() ); // <-- currentException = Exception
}
}
}
The order in which the application executes is:
main()
{
try
q()
{
try
catch
finally
}
catch
finally
}
It is well known that the finally block is executed after the the try and catch and is always executed....
But as you saw it's a little bit tricky sometimes check out those code snippet below and you will that
the return and throw statements don't always do what they should do in the order that we expect theme to.
Cheers.
/////////////Return dont always return///////
try{
return "In Try";
}
finally{
return "In Finally";
}
////////////////////////////////////////////
////////////////////////////////////////////
while(true) {
try {
return "In try";
}
finally{
break;
}
}
return "Out of try";
///////////////////////////////////////////
///////////////////////////////////////////////////
while (true) {
try {
return "In try";
}
finally {
continue;
}
}
//////////////////////////////////////////////////
/////////////////Throw dont always throw/////////
try {
throw new RuntimeException();
}
finally {
return "Ouuuups no throw!";
}
//////////////////////////////////////////////////
I think you just have to walk the finally blocks:
Print "1".
finally in q print "3".
finally in main print "2".
I think this solve the problem :
boolean allOk = false;
try{
q();
allOk = true;
} finally {
try {
is.close();
} catch (Exception e) {
if(allOk) {
throw new SomeException(e);
}
}
}
To handle this kind of situation i.e. handling the exception raised by finally block. You can surround the finally block by try block: Look at the below example in python:
try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data"