• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubts

 
Tanuja Vaid
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
a) Is it mandatory to have a defualt label in switch construct.
b)public class Test
{
static String j = "";
public static void method( int i)
{
try
{
if(i == 2)
{
throw new Exception();
}
j += "1";
}
catch (Exception e)
{
j += "2";
return;
}
finally
{
j += "3";
}
j += "4";
}
public static void main(String args[])
{
method(1);
method(2);
System.out.println(j);
}
}
In the above code why doesn't the statement after finally gets executed. In what scenario does the statement after finally is not executed.
Please explain.
TIA
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The output should be 13423, so the statement after the finally block, namely, j+="4" is not executed, when i==2.
When i==2 method() throws an exception inside a try block so it will be caught. Inside the catch block the function returns, so all subsequent code in method() will not be executed except for the finally block.
In what scenario does the statement after finally is not executed.

I took the liberty of tweaking your code a bit :

Output should be 1342, bypassing the finally block when i==2.
-anthony
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh I forgot...!
a) Is it mandatory to have a defualt label in switch construct.

No.
-anthony
 
Tanuja Vaid
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Anthony!
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whoops! I misunderstood the question
In what scenario does the statement after finally is not executed.

I thought "In what scenario does the statement in finally is not executed." Sorry
Okay, the statement after finally is not executed when:
(1) When your method returns inside a try, catch or finally block without thrrowing an exception, as we've done, and,
(2) when an exception is thrown inside a try, catch or finally block without being caught, and it propagates outwards.
-anthony
[ April 01, 2002: Message edited by: Anthony Villanueva ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic