• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception Q?

 
Dian He
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why following code will cause a compilation error. Thanks.
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);
}
}
}
 
Ragu Sivaraman
Ranch Hand
Posts: 464
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Dian He:
Why following code will cause a compilation error. Thanks.
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);
}
}
}


The exception is not propagated. Any checked exception thrown
by throw statement, or indirectly calling the method that can invoke this exception, must deal with this either, handling it on the spot (ie try/catch) or just declare it as throws some
exception.
Whoever calls this method, ie the caller will handle it
HTH

[This message has been edited by Ragu Sivaraman (edited August 10, 2001).]
 
Ashik Uzzaman
Ranch Hand
Posts: 2373
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Dian,
change ur first method signature from
static void throwMethod() to
static void throwMethod() to throws IllegalAccessException

------------------
azaman
 
Dian He
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Thanks, clear now.
So two ways to fix this, one is mentioned as above, another is putting into a try/catch block in the throwMethod, is it?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic