File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Jammi Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Jammi Question" Watch "Jammi Question" New topic
Author

Jammi Question

may leung
Greenhorn

Joined: Nov 28, 2000
Posts: 23
public class Test {
public static void main(String Args[]){
for (int i=0; i< 10; ++i){
try{
if( i%3 ==0) throw new Exception("EO");
try{
if(i%3==1) throw new Exception("E1");
System.out.println(i);
}catch(Exception inner){
i*=2;
} finally {
++i;
}
}catch (Exception outer){
i +=3;
}finally{
++i;
}
}
}
}
(choice: 4,5,6,7,8,9)The ans is 5 and 8.
Can anyone explain this in detail for me?
Thanks
alpa urja
Greenhorn

Joined: Dec 27, 2000
Posts: 17
This is your code and below is the explanation
class Test{
public static void main(String Args[]){
for (int i=0; i< 10; ++i){
try{
if( i%3 ==0) throw new Exception("EO");// stat 1
try{
if(i%3==1) throw new Exception("E1");//stat 2
System.out.println(i);
}catch(Exception inner){ //stat 3
i*=2;
} finally {
++i;
}
}catch (Exception outer){ //stat4
i +=3;
}finally{

++i;
}
}
}
}
at stat1
//when i=0,it throws Exception and goes corresponding catch{Exception outer},then i=3 and then executes finally block,so now i=4;Now it goes in the for loop and i=5(because of ++i)
now 5%3!=0 so it does not throw exception at stat1,then the control moves to stat2
again 5%3!=1 so does not throw exception at stat2..
So prints 5
then it excecutes both the finally statments and the i =7,then it moves in the
for loop (before going to the loop ,++i is done) so i=8 and i%3!=0 so does not thrwo exception at stat1,the then the control moves to stat2
again 8%3!=1 so does not throw exception at stat2..
So prints 8.Again executes both the finally statements and the i=10 so does not
go in the loop

Hope that helps

Alpa-urja
Cristi Tudose
Ranch Hand

Joined: Dec 25, 2000
Posts: 53
remember that finally always executed.
u have 2 try block.if you enter just in outer you execute only the outer finally.if you enter also in inner try, you'll execute both. so:
a.i=0;1st try block;exception thrown;don't enter 2nd try;catch outer i=3;finally outer i=4;
b.i=5(a & ++i from for statement);1st try block;enter the 2nd try;print 5(solution); inner finally i=6;outer finally i=7;
c.i=8(the same);1st try block;enter the 2nd try;print 8(solution); inner finally i=9;outer finally i=10... The End.
hope i was clear.
rgds,
Cristi
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Jammi Question