I know how try, catch & finally work (for most part), but I have one thing I was wondering: what happens with a return statement after a try-catch-finally, while we already had a return in the try (or catch)?
For example:
public boolean someMethod(){
boolean finished = false;
try{
// do something
return true;
}
catch(someException e){
// do something
}
finally{
// do something
}
return finished;
}
Let's say nothing went wrong in the try, so we returned true. Then we will go to the finally where we do something like closing a connection, and then?
Will the method stop after we did some stuff in the finally (so the method returned true in the try), or will the method continue after the finally again, resulting in returning finished (which is false)?
Thanks in advance for the responses.
The fact that the finally block is executed does not make the program forget you returned. If everything goes well, the code after the finally block won't be executed.
Here is an example that makes it clear:
public class Main {
public static void main(String[] args) {
System.out.println("Normal: " + testNormal());
System.out.println("Exception: " + testException());
}
public static int testNormal() {
try {
// no exception
return 0;
} catch (Exception e) {
System.out.println("[normal] Exception caught");
} finally {
System.out.println("[normal] Finally");
}
System.out.println("[normal] Rest of code");
return -1;
}
public static int testException() {
try {
throw new Exception();
} catch (Exception e) {
System.out.println("[except] Exception caught");
} finally {
System.out.println("[except] Finally");
}
System.out.println("[except] Rest of code");
return -1;
}
}
Output:
[normal] Finally
Normal: 0
[except] Exception caught
[except] Finally
[except] Rest of code
Exception: -1
If all goes well, return inside the try is executed after executing the finally block.
If something goes wrong inside try, exception is caught and executed and then finally block is executed and then the return after that is executed.
In that case the code inside the finally is run but the other return is skipped when there are no exceptions.
You may also see this for yourself by logging something :)
Also see this concerning System.exit:
How does Java's System.exit() work with try/catch/finally blocks?
And see returning from a finally:
Returning from a finally block in Java
public int Demo1()
{
try{
System.out.println("TRY");
throw new Exception();
}catch(Exception e){
System.out.println("CATCH");
}finally{
System.out.println("FINALLY");
}return 0;
}
the output of call to this method is like this
TRY
CATCH
FINALLY
0
Means Consider Try{}catch{}finally{} as sequence of statements executed one by one In this particular case.
And than control goes to return.
Definitely the code inside try will execute.. but when it reaches to return statement.. it will move to the finally block without executing the return statement in try block.. and then the code of finally will be executed and then the return statement of try will execute.
Related
I have a function which consists of a while loop.
Inside the while loop, I call a number of private methods.
If any of the methods fails (returns false, but also throws a private designed exception), I would like to continue strait to the next iteration.
example:
void func (){
while (true){
func1();
func2();
func3();
}
}
As I said, each func also throws myException object on error.
Thank you!
Wrap each function() call with a try-catch block. Like
while(true){
try{
func1();
}catch(YourException1 exception){
//Do something.
}
try{
func2();
}catch(YourException2 exception){
//Do something.
}
try{
func3();
}catch(YourException3 exception){
//Do something.
}
}
Put a try-catch block inside the loop.
Catch the exception and decide what to do:
void func (){
while (true){
try {
func1();
} catch (MyException e) {
// print error or don't do nothing
}
try {
func2();
} catch (MyException e) {
// print error or don't do nothing
}
try {
func3();
} catch (MyException e) {
// print error or don't do nothing
}
}
}
You could use the && operator to connect the function calls to not execute any after one of them failed and surround everything with a try-catch block.
void func (){
while (true){
try{ func1() && func2() && func3(); }
catch (YourCustomException e){ }
}
}
Not sure if this has already been answered, but.
I know that in java there is the try, catch and finally blocks, but is there one which is only called if try has no errors/exceptions?
Currently after stating the command that needs to be run, I'm setting a boolean to true, and after the try and catch block, the program checks for if the boolean is true.
I'm pretty sure that there is a much simpler way, help is appreciated!
Just put your code after the try...catch block and return in the catch:
boolean example() {
try {
//dostuff
} catch (Exception ex) {
return false;
}
return true;
}
This would also work if you put the return true at the end of the try block as the code would jump to the catch on error and not execute the rest of the try.
void example() {
try {
//do some stuff that may throw an exception
//do stuff that should only be done if no exception is thrown
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
No, there is no block called only if no exceptions were raised.
The catch block is called if there were exceptions, finally is called regardless.
As stated, you can emulate such a beast with something like:
bool completed = false;
try {
doSomeStuff();
completed = true;
} catch (Exception ex) {
handleException();
} finally {
regularFinallyHandling();
if (completed) {
thisIsTheThingYouWant();
}
}
but there's nothing built into the language itself that provides this functionality.
What is the behavior of catch block, if it is not at the end of the block.
private Boolean connect(String addr) {
.....
try {
connected = true;
} catch (ExceptionType name) {
//log // print stack trace etc, but no explicit return
} catch (ExceptionType name) {
}
if (some_other_condn) {
..
}
}
Do one need return inside catch block if I don't want to execute rest of the code in the block?
Yes you do need to return from the catch block if you don't want to execute rest of the code.
Or, better just put the rest of the code within the try block itself.
try {
connected = true;
if (some_other_condn) {
//...
}
} catch (ExceptionType name) {
//log // print stack trace etc, but no explicit return
} catch (ExceptionType name) {
}
Yes, that is correct. If you don't want to execute rest of the code, you need to return (But you will be returned on exception case only, I hope you know about that). Success case your return statement won't execute.
I have a problem understanding how the try{} catch(Exception e){...} works!
Let's say I have the following:
try
{
while(true)
{
coord = (Coordinate)is.readObject();//reading data from an input stream
}
}
catch(Exception e)
{
try{
is.close();
socket.close();
}
catch(Exception e1)
{
e1.printStackTrace();
}
}
Section 2
try
{
is.close();
db.close();
}
catch(Exception e)
{
e.printStackTrace();
}
Let's say my while() loop throws an error because of an exception of is stream.
This will get me out of the infinite loop and throw me in the first catch(){............}
block.
My question is the following:
After throwing an exception, getting out of the loop while() and reaching to
catch(){
}
Will my program continue his execution and move on to section 2? As long as the exception was caught? Or everything ends in the first catch()?
I think you want to use finally after your first catch [catch (Exception e)] to close your streams:
try {
// Do foo with is and db
} catch (Exception e) {
// Do bar for exception handling
} finally {
try {
is.close();
db.close();
} catch (Exception e2) {
// gah!
}
}
As long as no exceptions are thrown in your catch clause, your program will continue execution after your catch (or finally) clause. If you need to rethrow the exception from the catch clause, use throw; or throw new Exception(ex). Do not use throw ex, as this will alter the stack trace property of your exception.
After the exception is caught, execution continues after the try/catch block. In this case, that's your section 2.
An uncaught exception will terminate the thread, which might terminate the process.
Yes, you are right. It will move to Section 2.
If you want your Section 2 bound to happen, irrespective of any exception generated, you might want to enclose them in a finally block.
try {
// Do foo with is and db
}
catch (Exception e) {
// Do bar for exception handling
}
// Bound to execute irrespective of exception generated or not ....
finally {
try {
is.close();
db.close();
}
catch (Exception e2) {
// Exception description ....
}
}
What happens if you throw an error in a finally block? Does it get handled in one of the corresponding catch clauses?
Only if you put another try-catch block in the finally block. Otherwise it's an error like any other.
You need to include try-catch blocks inside the finally or catch blocks.
e.g.:
try {
// your code here
} finally {
try {
// if the code in finally can throw another exception, you need to catch it inside it
} catch (Exception e) {
// probably not much to do besides telling why it failed
}
} catch (Exception e) {
try {
// your error handling routine here
} catch (Exception e) {
// probably not much to do besides telling why it failed
}
}
It will not handle exception until it is caught in finally block it self.
public static void main(String[] args) throws Exception {
try {
System.out.println("In try");
} catch (Exception e) {
System.out.println("In catch");
} finally{
throw new Exception();
}
}
Above code will throw exception but if you do as follows it will work:
public static void main(String[] args){
try {
System.out.println("In try");
} catch (Exception e) {
System.out.println("In catch");
} finally{
try{
throw new Exception();
}catch(Exception e){}
}
}
Nope. It would be caught by a catch where then entire try/catch/finally was nested within another try/catch. The exception would otherwise be thrown out of the function, and would be handled by the caller of the function.
No it doesn't. You will have to handle with it IN the finally block or define a proper throw declaration in the method description.
No, a catch block can only catch exceptions thrown within the corresponding try block - not a finally block. (Of course, if that finally block is within another try block, the catch clauses for that try block are still used.)
The relevant section in the JLS is 14.20.2. Each of the flows listed there has something like this:
If the finally block completes abruptly for any reason, then the try statement completes abruptly for the same reason.
In other words, there's no attempt for any catch clauses associated with the finally block to handle the exception.
The order of execution is normally directly indicated by the order of statements: 1. try, 2. catch exceptions in the specified order (only one catch is executed), 3. finally.
So when the finally block is executed (note that this is always the case, even in the case of a return statement or exception being thrown in the try or catch blocks) the execution of try statement is in its last phase and thus it cannot catch further throwables. As already pointed out, the exception has to be handled in a location further down the stack (or up, depends on the view point ;) ).