This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception Problem

 
Jyotsna Umesh
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi JavaRanchers,
Please explain why the answer to this problem is compilation error?
public class ThrowsDemo {
static void throwMethod() {
System.out.println("Inside throwMethod.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwMethod();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
[a] Compilation error
[b] Runtime error
[c] Compile successfully, nothing is printed.
[d] inside demoMethod. followed by caught: java.lang.IllegalAccessException: demo
Thanx
Jyotsna
 
Scott Appleton
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jyotsna,
If a method can or does throw a checked Exception, then it must either declare that it does via a "throws" clause in the method signature

or else it must place the statement which may throw a checked exception within a try-catch block

The code you posted does neither, so the compiler complains.
 
Jyotsna Umesh
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Scott for the explanation, its silly of me, i didn't check this.
Jyotsna
Originally posted by Scott Appleton:
[B]Jyotsna,
If a method can or does throw a checked Exception, then it must either declare that it does via a "throws" clause in the method signature

or else it must place the statement which may throw a checked exception within a try-catch block

The code you posted does neither, so the compiler complains.[/B]

 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic