Why such output is coming? - java

It might be easy but I don't understand why the output is coming as 1 4. And what is the function of the return statement at Line 9?
public static void main(String[] args) {
try{
f();
} catch(InterruptedException e){
System.out.println("1");
throw new RuntimeException();
} catch(RuntimeException e){
System.out.println("2");
return; \\ Line 9
} catch(Exception e){
System.out.println("3");
} finally{
System.out.println("4");
}
System.out.println("5");
}
static void f() throws InterruptedException{
throw new InterruptedException("Interrupted");
}
Thanks in advance.

Your function f() throws InterruptedException, which is caught by the first catch block (hence it prints 1), but this catch block cannot throw other exceptions (if it is not thrown by your method), Hence, no other catch block can catch your excception and therefore finally is executed (finally executes in every case except those silly infinite loop cases). you can refer to Exception thrown inside catch block - will it be caught again?.
I hope it helps.
Just to summarize, you can throw any exception from try block & it will be caught (if there is a good catch block). But from catch block only those exceptions can be thrown (and consequently caught by) which your method throws.
If you throw exception from catch block which are not thrown by your method, it is meaning less and won't be caught (like in your case).

As you can see f() throws InterruptedException, so it will first print 1 which is inside first catch block and then finally would execute so it will print 4.

The 1 is printed because f() throws an InterruptedException. Because the Exception is handled in the first catch block it is not handled in the other exception blocks belower anymore. The finally statement is always run, so the 4 is printed too.

try{
f();
} catch(InterruptedException e){
System.out.println("1");
throw new RuntimeException(); // this RuntimeException will not catch by
//following catch block
} catch(RuntimeException e){
You needs to change your code as follows to catch it.
try{
f();
} catch(InterruptedException e){
System.out.println("1");
try {
throw new RuntimeException();// this RuntimeException will catch
// by the following catch
}catch (RuntimeException e1){
System.out.println("hello");
}
} catch(RuntimeException e){
System.out.println("2");
return;
} catch(Exception e){
System.out.println("3");
} finally{
System.out.println("4");
}
System.out.println("5");
Then your out put"
1
hello // caught the RunTimeException
4 // will give you 2,but also going to finally block then top element of stack is 4
5 // last print element out side try-catch-finally

f() throws an InterruptedException so you get the 1. finally is always called at the end so you get the 4.

As f() throw InterruptedException which executes,
catch(InterruptedException e){
System.out.println("1");
throw new RuntimeException();
}
prints --> 1
and finally gets executed before exiting the program,
finally{
System.out.println("4");
}
prints --> 4
Code after return wont execute but finally will get executed.

Related

Java - catch/rethrow behavior [duplicate]

This question already has answers here:
Exception thrown in catch and finally clause
(12 answers)
Closed 1 year ago.
I have this piece of Java code.
void convertFile() {
try{
.....
}catch (Exception e) {
logError("Error in convertJsonFile", e);
throw e;
}finally{
if (writer!=null) {
writer.close();
writer = null;
}
if (fos!=null) {
fos.close();
fos = null;
}
ms2 = System.currentTimeMillis();
logInfo(String.format("Time elapsed: %d seconds.", ((ms2-ms1)/1000)));
logInfo("File conversion complete.");
}
return f + "_changed.xml";
}
The catch block logs and rethrows the Exception.
But it seems the finally block also throws a RuntimeException.
Will the finally block be executed if the catch block rethrows Exception as done here?
If I remember correctly finally block will be executed even in this case.
OK if so... what will happen if we enter the catch block (it rethrows), then we enter the finally block, and the finally block also throws a RuntimeException at this line writer.close(); ? Which exception will be thrown from this whole method - the rethrown one from the catch block, or the RuntimeException from the finally block?!
I think the RuntimeException will be the final outcome of the method and we will never reach the line in the catch block which rethrows. Because I guess the line which rethrows is executed after the finally block. But I am not sure. I got really confused.
Could someone clear my doubts here?
Seems I have forgotten some of these details.
And I have no decent access to the logs, they are in Elastic/Kibana and access to them is a real pain.
Yes, finally block will be executed
The exception from finally block will be thrown in this case. Thus, exception from catch block will be lost.

how to terminate finally block and execute rest of the code outside the try...catch...finally block

public static void main(String[] args) {
try{
System.out.println("This is try block...!!");
}
catch(Exception e)
{
System.out.println("Exception is "+e);
}
finally
{
System.exit(0);//terminates finally block
System.out.println("This is finally block");
}
System.out.println("This is outside the try catch block...");
}
In above code i got output like this "This is try block...!!"
But i want output such that,
"This is try block...!!"
"This is outside the try catch block...!!"
can any one give me correct solution for this problem? and how can i get output as i want?does any one explain me please?
it's only for your situation if you want to skip execution of finally block when try is success.
boolean trySuccessflag = false;
try{
System.out.println("This is try block...!!");
trySuccessflag = true;
}
catch(Exception e)
{
System.out.println("Exception is "+e);
}
finally
{
if(!trySuccessflag){
System.out.println("This is finally block");
}
}
System.out.println("This is outside the try catch block...");
I think it may be so...
public static void main(String[] args) {
try{
System.out.println("This is try block...!!");
} catch(Exception e) {
System.out.println("Exception is "+e);
}
System.out.println ("This is outside the try catch block...");
}
Your "System.exit(0);" is before your "System.out.println ("This is outside the try catch block...")". So It doesn't work.
Remove this instruction :
System.exit(0);//terminates finally block
It stop the application not terminate the finally block
Your question has already an answer here
Your problem :
First you have to know that finally block is always executed, either you succeed or fail the try block.
Second, System.exit(0) exit the System. So the JVM. Not the Try block. So when you call your program simply terminates that's why nothing more is printed.
Solution :
First if you don't want to execute the Finally block, just do not write it. It makes no sense to write a code you don't want to execute.
Second, if you really need to exit the finally block use break; instead of System.exit(0);

surround "throw new Exception()" with try catch

throw new Exception();
If you put this statement in a method, you should either add throws Exception after the method name. Or, you can surround the statement with try-catch.
try {
throw new Exception();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But what is it the point here? The compiler permit it, so I just want to know if it is designed intentionally. I am curious.
Actually, this is useful in some scenarios.
Say, you want to perform a series of tasks and if any one of them fails, you want to abort the sequence and do some other task.
It is true that you can do the same with a series of if statements, but this provides another way to do it.
try{
// do task 1
// if failed, throw new Exception("Task 1 Failed");
// do task 2
// if failed, throw new Exception("Task 2 Failed");
// do task 3
// if failed, throw new Exception("Task 3 Failed");
...
}catch(Exception e){
// System.err.println(e.getMessage());
// do somthing else
}

Java exception not caught?

I have a small theoretical problem with try-catch constructions.
I took a practical exam yesterday about Java and I don't understand following example:
try {
try {
System.out.print("A");
throw new Exception("1");
} catch (Exception e) {
System.out.print("B");
throw new Exception("2");
} finally {
System.out.print("C");
throw new Exception("3");
}
} catch (Exception e) {
System.out.print(e.getMessage());
}
The question was "what the output will look like?"
I was pretty sure it would be AB2C3, BUT suprise suprise, it's not true.
The right answer is ABC3 (tested and really it's like that).
My question is, where did the Exception("2") go?
From the Java Language Specification 14.20.2.:
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).
So, when there is a catch block that throws an exception:
try {
// ...
} catch (Exception e) {
throw new Exception("2");
}
but there is also a finally block that also throws an exception:
} finally {
throw new Exception("3");
}
Exception("2") will be discarded and only Exception("3") will be propagated.
Exceptions thrown in finally block suppress the exception thrown earlier in try or catch block.
Java 7 example: http://ideone.com/0YdeZo
From Javadoc's example:
static String readFirstLineFromFileWithFinallyBlock(String path)
throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
}
However, in this example, if the methods readLine and close both throw
exceptions, then the method readFirstLineFromFileWithFinallyBlock
throws the exception thrown from the finally block; the exception
thrown from the try block is suppressed.
The new try-with syntax of Java 7 adds another step of exception suppression: Exceptions thrown in try block suppress those thrown earlier in try-with part.
from same example:
try (
java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);
java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
) {
for (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements();) {
String newLine = System.getProperty("line.separator");
String zipEntryName = ((java.util.zip.ZipEntry)entries.nextElement()).getName() + newLine;
writer.write(zipEntryName, 0, zipEntryName.length());
}
}
An exception can be thrown from the block of code associated with the
try-with-resources statement. In the above example, an exception can
be thrown from the try block, and up to two exceptions can be thrown
from the try-with-resources statement when it tries to close the
ZipFile and BufferedWriter objects. If an exception is thrown from the
try block and one or more exceptions are thrown from the
try-with-resources statement, then those exceptions thrown from the
try-with-resources statement are suppressed, and the exception thrown
by the block is the one that is thrown by the
writeToFileZipFileContents method. You can retrieve these suppressed
exceptions by calling the Throwable.getSuppressed method from the
exception thrown by the try block.
In code from question, each block is plainly discarding the old exception, not even logging it, not good when you are trying to resolve some bugs:
http://en.wikipedia.org/wiki/Error_hiding
Since throw new Exception("2"); is thrown from catch block and not try, it won't be caught again.
See 14.20.2. Execution of try-finally and try-catch-finally.
This is what happening:
try {
try {
System.out.print("A"); //Prints A
throw new Exception("1");
} catch (Exception e) {
System.out.print("B"); //Caught from inner try, prints B
throw new Exception("2");
} finally {
System.out.print("C"); //Prints C (finally is always executed)
throw new Exception("3");
}
} catch (Exception e) {
System.out.print(e.getMessage()); //Prints 3 since see (very detailed) link
}
Your Question is very obvious, and the answer is simple to the same extent..
The Exception object with message as "2" is overwritten by the Exception object with message as "3" .
Explanation :
When an Exception occur, its object it thrown to catch block to handle. But when exception occur in catch block itself, its object is transferred to OUTER CATCH Block(if any) for exception Handling. And Same happened Here. The Exception Object with message "2" is transferred to OUTER catch Block . But wait.. Before leaving inner try-catch block it HAS TO EXECUTE FINALLY. Here occurred the change we are concerned about. A new EXCEPTION object(with message "3") is thrown out or this finally block which replaced the already thrown Exception object(with message "2").As a result of which, when the message of Exception object is printed , we got overridden value i.e. "3" and not "2".
Keep Remember :Only one exception object can be handled by on CATCH block.
The finally block always runs. Either you return from inside the try block or an exception is thrown. The exception thrown in the finally block will override the one thrown in the catch branch.
Additionally, throwing an exception will not cause any output by itself. The line throw new Exception("2"); will not write anything out.
According to your code:
try {
try {
System.out.print("A");
throw new Exception("1"); // 1
} catch (Exception e) {
System.out.print("B"); // 2
throw new Exception("2");
} finally { // 3
System.out.print("C"); // 4
throw new Exception("3");
}
} catch (Exception e) { // 5
System.out.print(e.getMessage());
}
As you can see here:
print A and throws exception # 1;
this exception has caught by catch statement and print B - # 2;
block finally # 3 executes after try-catch (or only try, if hadn't occurred any exception) statement and prints C - # 4 and thrown new exception;
this one has caught by external catch statement # 5;
Result is ABC3. And 2 is omitted at the same way as 1

Java catching exceptions and subclases

Hello,
In Java if a method like BufferedReader.read() says it can throw an IOException and I try to catch a FileNotFoundException and an IOException in two catch blocks, what catch blocks will be entered if the file doesn't exist?
Does it enter only the most specific or both?
The first coded catch that matches the exception will be entered.
Edited to incorporate comment from Azodius
For example:
try {
bufferedReader.read();
} catch (FileNotFoundException e) {
// FileNotFoundException handled here
} catch (IOException e) {
// Other IOExceptions handled here
}
This following code does not compile:
try {
bufferedReader.read();
} catch (IOException e) {
// All IOExceptions (and of course subclasses of IOException) handled here
} catch (FileNotFoundException e) {
// Would never enter this block, because FileNotFoundException is a IOException
}
Compiler message says:
Unreachable catch block for FileNotFoundException. It is already handled by the catch block for IOException
Only the first catch block encountered where the exception type of the catch block matches the type of the exception being thrown will be run (more specifically, the first catch block where (e instaceof <exception type>)==true will be run). None of the other catch blocks will be run.
For example
try{
BufferedReader.read();
}
catch(FileNotFoundException e){System.out.println("FileNotFoundException");}
catch(IOException e){System.out.println("IOException");}
Will print FileNotFoundException if BufferedReader.read() throws a FileNotFoundException.
Note that the following doesn't actually compile:
try{
BufferedReader.read();
}
catch(IOException e){System.out.println("IOException");}
catch(FileNotFoundException e){System.out.println("FileNotFoundException");}
because Java realizes that it is not possible for the FileNotFoundException to be caught because all FileNotFoundExceptions are also IOExceptions.
The first one which is suitable for that type of exception (and only that). So if you catch the two exception types above in the order you list them, a FileNotFoundException will be caught.
Specific exception is caught first. and it's a compile time error if generic exception is caught befor specific one.

Categories

Resources