Doubts reg try block and return statements

hi

public int test()

{

try

{

System.out.println("hi");

return 1;

}

catch(Exception e)

{

System.out.println("err");

return 2;

}

finally

{

System.out.println("final");

return 3;

}

//System.out.println("after");

//return 4;

}

when i call this function, it will printing 3... why ?

and also compilation error is coming when i put return statement after final block.. why is it so?

[519 byte] By [HimSSSa] at [2007-11-27 11:14:40]
# 1

> when i call this function, it will printing 3...

> why ?

Because finally is always executed...

> nd also compilation error is coming when i put return

> statement after final block.. why is it so?

"unreachable statement". If all those blocks return, how would you get to the last return statement?

Besides, please simply don't bother and just don't write code like this.

CeciNEstPasUnProgrammeura at 2007-7-29 14:08:13 > top of Java-index,Java Essentials,New To Java...
# 2

but if commented the return statements in catcch and finally then it iam not getting any compilation error.

public int test()

{

try

{

System.out.println("hi");

return 1;

}

catch(Exception e)

{

System.out.println("err");

// return 2;

}

finally

{

System.out.println("final");

//return 3;

}

System.out.println("after");

return 4;

}

and iam just learning ..... regarding return and try block

HimSSSa at 2007-7-29 14:08:13 > top of Java-index,Java Essentials,New To Java...
# 3

> but if commented the return statements in catcch and

> finally then it iam not getting any compilation

> error.

Do you expect to?

By the way, you should never return, throw, break, or continue out of a finally block.

When you post code, please use[code] and [/code] tags as described in Formatting tips on the message entry page. (http://forum.java.sun.com/help.jspa?sec=formatting) It makes it much easier to read.

jverda at 2007-7-29 14:08:13 > top of Java-index,Java Essentials,New To Java...
# 4

"but if commented the return statements in catcch and finally then it iam not getting any compilation error."

Because you commented out the return statement in the finally statement, anything after the finallly block is now reachable. Therefore no 'cant reach statement' error. Now if you try to justify this bad code any more, we'll have to track you down and remove your computer :o

George123a at 2007-7-29 14:08:13 > top of Java-index,Java Essentials,New To Java...
# 5

hey iam not justifying the code .. i know it is not good practice to write like that . just i want get grip on working of the return statement...

anyway now i have clear idea how the retrun statement will wrk...

thanks alot to every one

HimSSSa at 2007-7-29 14:08:13 > top of Java-index,Java Essentials,New To Java...