-6
try {
    statement 1  // executing successfully
    statement 2  // Exception Occured
    statement 3  // Skip Execution
} catch(Exception e) {
    e.printstacktrace();
} finally {
    statement 4
}

the above code is the basic of trycatch block.Here if st2 failed then st3 is going to execute.So is there any way where we can execute st3 after st2 fails??

one of the interview Question in java
Community
  • 1
  • 1
RAJESHPODDER007
  • 733
  • 1
  • 8
  • 14
  • 4
    "*Here if st2 failed then st3 is going to execute*" - no. If statement 2 failes with an exception, statement 3 will **not** be executed. –  Apr 21 '14 at 07:32
  • 1
    Move it to the finally block if you want it to be executed always, or catch block if you want it to be executed only when Exception happened. – songyuanyao Apr 21 '14 at 07:34

3 Answers3

2

Surround statement 2 with another try catch block. In this case statement 3 will execute even after statemnt 2 has fauled. If you want statement 3 to execute only after statemnt 2 fails. Move statemnt 3 to catch block

jasleen
  • 61
  • 1
  • 4
0

Not it wont. Java reads code line by line. So when s2 failed it will go to the catch block. Anyhow s4 will be executed anyhow. So you can bring the s3 to finally block where it will executed even s2 failed.

try{
    statement 1  // executing successfully
    statement 2  // Exception Occured    
}catch(Exception e){
    e.printstacktrace();
}finally{
    statement 3  // Skip Execution
    statement 4
}

S3 will be executed in above example.

try{
    statement 1  // executing successfully
try{
    statement 2  // Exception Occured
}catch(Exception e){
}
    statement 3  // Skip Execution
}catch(Exception e){
    e.printstacktrace();
}finally{
    statement 4
}

S3 will executed in above example as well.

chinna_82
  • 6,353
  • 17
  • 79
  • 134
0

Please read the java exception handling carefully it is not that complex.

vaibhav
  • 3,929
  • 8
  • 45
  • 81