Exception thrown inside catch block - will it be caught again? - java

This may seem like a programming 101 question and I had thought I knew the answer but now find myself needing to double check. In this piece of code below, will the exception thrown in the first catch block then be caught by the general Exception catch block below?
try {
// Do something
} catch(IOException e) {
throw new ApplicationException("Problem connecting to server");
} catch(Exception e) {
// Will the ApplicationException be caught here?
}
I always thought the answer would be no, but now I have some odd behaviour that could be caused by this. The answer is probably the same for most languages but I'm working in Java.

No, since the new throw is not in the try block directly.

No. It's very easy to check.
public class Catch {
public static void main(String[] args) {
try {
throw new java.io.IOException();
} catch (java.io.IOException exc) {
System.err.println("In catch IOException: "+exc.getClass());
throw new RuntimeException();
} catch (Exception exc) {
System.err.println("In catch Exception: "+exc.getClass());
} finally {
System.err.println("In finally");
}
}
}
Should print:
In catch IOException: class java.io.IOException
In finally
Exception in thread "main" java.lang.RuntimeException
at Catch.main(Catch.java:8)
Technically that could have been a compiler bug, implementation dependent, unspecified behaviour, or something. However, the JLS is pretty well nailed down and the compilers are good enough for this sort of simple thing (generics corner case may be a different matter).
Also note, if you swap around the two catch blocks, it wont compile. The second catch would be completely unreachable.
Note the finally block always runs even if a catch block is executed (other than silly cases, such as infinite loops, attaching through the tools interface and killing the thread, rewriting bytecode, etc.).

The Java Language Specification says in section 14.19.1:
If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:
If the run-time type of V is assignable to the Parameter of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed. If that block completes normally, then the try statement completes normally; if that block completes abruptly for any reason, then the try statement completes abruptly for the same reason.
Reference:
http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html#24134
In other words, the first enclosing catch that can handle the exception does, and if an exception is thrown out of that catch, that's not in the scope of any other catch for the original try, so they will not try to handle it.
One related and confusing thing to know is that in a try-[catch]-finally structure, a finally block may throw an exception and if so, any exception thrown by the try or catch block is lost. That can be confusing the first time you see it.

If you want to throw an exception from the catch block you must inform your method/class/etc. that it needs to throw said exception. Like so:
public void doStuff() throws MyException {
try {
//Stuff
} catch(StuffException e) {
throw new MyException();
}
}
And now your compiler will not yell at you :)

No -- As Chris Jester-Young said, it will be thrown up to the next try-catch in the hierarchy.

As said above...
I would add that if you have trouble seeing what is going on, if you can't reproduce the issue in the debugger, you can add a trace before re-throwing the new exception (with the good old System.out.println at worse, with a good log system like log4j otherwise).

It won't be caught by the second catch block. Each Exception is caught only when inside a try block. You can nest tries though (not that it's a good idea generally):
try {
doSomething();
} catch (IOException) {
try {
doSomething();
} catch (IOException e) {
throw new ApplicationException("Failed twice at doSomething" +
e.toString());
}
} catch (Exception e) {
}

No, since the catches all refer to the same try block, so throwing from within a catch block would be caught by an enclosing try block (probably in the method that called this one)

Old post but "e" variable must be unique:
try {
// Do something
} catch(IOException ioE) {
throw new ApplicationException("Problem connecting to server");
} catch(Exception e) {
// Will the ApplicationException be caught here?
}

Related

What is the purpose of throwing all caught exceptions?

I'm going through our code for our core programs to refactor and I encountered this weird try/catch block
try {
//Do some socket and network stuff
} catch (NoRouteToHostException e) {
throw e;
} catch (UnknownHostException e) {
throw e;
} catch (IOException e) {
throw e;
} finally {
//Does some counting stuff over here
}
Now I can't understand why on earth someone would do something like this, the people who wrote this code have left the company, but were indeed very skilled.
Is there a purpose to this try/catch block? Would it not be better to just throw these exceptions and do the finally things from where the method is called?
If you do literally nothing with the exception before you rethrow it, there is no point in catching it. Remove the catch block for that particular exception.
try doesn't need any catch blocks, provided there is a finally.
Note that catch (SomeException e) {} is doing something with the exception: it is swallowing it (which is likely not advisable anyway). As such, you cannot remove this without changing semantics.
The only exception (no pun intended) is if you don't want to catch a particular subclass of an otherwise-caught exception. For example:
try {
} catch (FileNotFoundException e) {
throw e;
} catch (IOException e) {
// Do something.
}
If you were to remove the catch/rethrow of FileNotFoundException, it would change the semantics because it would be handled by the more-general IOException. As written, a FNFE will "leap frog" the catch block for IOE.
(This is only very occasionally useful).
Either they didn't know they could write try-finally without catch or it's a legacy piece and it formerly performed something different for each catch block.
Otherwise, it makes no sense and it's identical to
try {
// Do some socket and network stuff
} finally {
// Does some counting stuff over here
}
Even skilled people tend to make mistakes, particularly when a deadline approaches.
If you throw every exception you catch, you will end up with an unhandled exception and your application will crash. At some point in your code, you will have to decide how you will deal with the error. If you are writing a GUI application this may be at the GUI layer, where you display an error message to your user. However, throwing all exceptions caught is no different to simply marking your method with throws IOException, ....
Also, since Java 7, you can use try-with-resources, for example:
try (Socket socket = serverSocket.accept()) {
socket.getInputStream() // whatever
} catch (IOException e) {
doSomething(e);
}
Note that you can still omit the catch block and simply pass the exception up to the enclosing scope.

Significance of finally block [duplicate]

This question already has answers here:
Why use finally instead of code after catch [duplicate]
(14 answers)
Closed 5 years ago.
What is the significance of the Finally block in a Try...[Catch]...Finally block?
Isn't this code
Resource r;
try{
r = new Resource();
r.methodThatThrowsException();
} catch (Exception e) {
e.printStackTrace()
} finally {
r.close()
}
equivalent to
Resource r;
try{
r = new Resource();
r.methodThatThrowsException();
} catch (Exception e) {
e.printStackTrace()
}
r.close()
? I would understand if they have the same scope, but the fact that I have to define Resource r outside the try block anyway to use it in the finally block means that I see no advantage to using a finally block.
Am I missing something? Is there a certain case that I haven't thought of that requires a Finally block?
In this case, they are equivalent since (a) the code catches any exception, including runtime exceptions that are thrown and (b) the catch block doesn't rethrow the exception, so the execution continues.
The finally block is generally used to ensure resource release in cases where either (a) or (b) don't hold. In newer Java implementations, wherever possible, you should use try-with-resources instead.
The two code snippets are different: the second one will not close if exception handling block ends in another exception.
Here is an illustration:
public static void one() throws Exception {
try {
System.out.println("One");
throw new Exception();
} catch (Exception e) {
System.out.println("Catch one");
if (2 != 3) throw new Exception(); // "if" silences compiler's check
} finally {
System.out.println("Finally one");
}
}
public static void two() throws Exception {
try {
System.out.println("Two");
throw new Exception();
} catch (Exception e) {
System.out.println("Catch two");
if (2 != 3) throw new Exception(); // "if" silences compiler's check
}
System.out.println("After two");
}
The call to one() prints Finally one, while After two never gets printed (demo 1).
The finally block becomes even more important when you catch specific exceptions (blindly catching Exception is nearly always a bad idea), because the try block may bypass your cleanup code by throwing an exception that you do not catch. Here is another illustration:
public static void error() throws Exception {
try {
System.out.println("Try");
throw new Error();
} catch (Exception e) {
System.out.println("Catch");
throw new Exception();
} finally {
System.out.println("Finally");
}
}
This code prints Try and Finally, without Catch in the middle, because Error is not caught in the catch block (demo 2).
It goes without saying that human readers of your program will have easier time locating you clean-up code if you place it in the finally block.
No, it is not equivalent. In the first snippet r.close() will be always called, while in the second snippet r.close() might not be called:
when the try block throws an Error (what might happen when you use assertions and an assertion fails)
when the exception handler throws another Exception
To ensure the resources are always released close() method should be called from finally blocks.

Why do we need "try" keyword?

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 .

Should you catch all exceptions in your main method

Is it correct to catch everything into the main? If not, why?
public static void main(String[] args) {
try {
// A lot
// of
// calls
} catch (Exception e) {
e.printStackTrace();
}
}
Generally it's better to separate out the catches IMO, so that you can handle each separately even if you end up handling these the same. It's also easier to see what the risks are, what the catch is, when you come back to your code. Just a quick example:
try {
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (IOException e) {
request.abort();
} finally {
client.close();
}
If all you do is call e.printStacktrace (), I do not think it is worthwhile. The JVM will do something like that anyway. But I believe it is worthwhile if you output a meaningful message; stacktraces are meaningful only to programmers.
It will catch every Exception from the try{} block, It might not catch if there is another catch catching in the inner code
It depends. If you only need to show some error messages when an exception arise, I guess it's ok. But if you find the need to make some kind of processing depending on the type of exception, then you'll be better off try-catching in the inner code.
In your case it makes no sense since you do not process the exception you catch but simply print it. If you declare main throws checked_exceptions_your_code_throws_list you will get the same result (JVM will print exception) and a cleaner code. And if your code throws no checked exception then do not declare any exceptions at all.

Difference between finally and write after catch

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..

Categories

Resources