• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

Exception Handling  RSS feed

 
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
 
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.
 
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
 
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
Boost this thread!