This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception Handling

 
Swati Thorve
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anybody explain me the o/p of following code

public class Question46{
public static void main(String[] args) throws Exception{
try{
int i=5/(int)Math.random();
System.out.println("i="+i);
} catch(ArithmeticException ae) {
throw new Exception("thrown from first catch");
} catch(Exception e){
throw new Exception("thrown from second catch");
} finally {
return;
}
}
}

options are

A. An exception is thrown and the exception message thrown from first catch is diplayed with the exception stack trace.
B. An exception is thrown and the exception message thrown from second catch is diplayed with the exception stack trace.
C. Prints nothing.
D. Compilation error.
E. Prints i=? where ? stands for the generated random value.


Correct option is C
Plz explain me how?

Bye
-Swati
 
Narasimhan Madangopalan
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In this code we are dividing by (int)Math.random() this always gives zero(since Math.random() returns a number between 0.0 and 0.99 when this converted to int it always yields zero) and this smoothly terminates because a finally with a return statement can nullify
the exception.

Cheers,
Narasi
 
Swati Thorve
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Narasimhan.
 
vinod awar
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
any exception thrown from a catch block will not be caught in subsequent catch blocks.and while returning return value of finally block hides any previous value
 
Anju sethi
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but as per my understanding finally block nullify any previously thrown exception if at all finally block code throws some exception.

But here finally block simply returns the control.how is it nullifying previous exception

Could u please explain.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic