• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Q from Dan'S Exception

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Guys
chk this
class RedException extends Exception {}
class BlueException extends Exception {}
class White {
void m1() throws RedException {throw new RedException();}
public static void main (String[] args) {
White white = new White();
int a,b,c,d;
a = b = c = d = 0;
try {white.m1();a++;}
catch (RedException e) {b++;}
catch (BlueException e) {c++;}
finally {d++;}
System.out.print(a+","+b+","+c+","+d);
}
}

What is the result of attempting to compile and run the program?
Dans answer is
A compile-time error is generated because the second catch clause attempts to catch an exception that is never thrown in the try block.
My doubt is whether its a neccessity to throw only those exceptions that are stated to be thrown
Best
Mandeep
 
Ranch Hand
Posts: 867
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi Mandeep
My doubt is whether its a neccessity to throw only those exceptions that are stated to be thrown
I think it is a tricky question
You can help me to check it out too.
If you claim to throw Unchecked exception that is not necessary to explicit be thrown,when you whether want to throw it or not.
But checked exception is necessary to explicit be thrown and catched it,when you first claim it.
if you change a little bit of the following case,I hope that you can find out the answer.
First case:

Second case:

Hope you find out the answer
 
Ranch Hand
Posts: 160
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I came across this question as well. The compiler is aware of which methods throw exceptions and it can catch unnecessary code like this.
However, there is one exception to this rule (no pun intended).
You can catch the generic Exception without a compiler error, even if nothing within the try block throws an exception. Otherwise, the compiler will bark at you if you try to catch an exception.

[ June 16, 2003: Message edited by: Brian Joseph ]
 
reply
    Bookmark Topic Watch Topic
  • New Topic