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

RuntimeException v/s IllgealAccessException ?

 
vijay gardiner
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've a program A :
class A {
static void demoproc() {
try {
System.out.println("inside demoproc: ");
throw new RuntimeException("demo");
} finally {System.out.println("finally in A "); }
}
public static void main(String args[]){
try {
demoproc();
} catch(RuntimeException e) {
System.out.println("caught ");
}
}
}

I've program B like :
class B {
static void demoproc() {
try {
System.out.println("inside demoproc: ");
throw new IllegalAccessException("demo");
} finally {System.out.println("finally in A "); }
}
public static void main(String args[]){
try {
demoproc();
} catch(IllegalAccessException e) {
System.out.println("caught ");
}
}
}
The program "A" works, but "B" end in compilation errors, the only difference between the above two is "RuntimeException" and "IllegalAccessException", why is that? Could anyone explain that please??
Vijay
 
Roy Ben Ami
Ranch Hand
Posts: 732
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
RuntimeException is a runtime exception
that means that if u want to throw one of those u dont need to declare it in the method that throws it.
however IllegalAccessEXception is a checked exception.
that means that the method that throws one of those need to declare it.
add this to the method declaration:
static void demoproc() throws IllegalAccessException
then it will compile and run.
(notice the s in throws ) which means we just delaring to the compiler that this method may throw an exception of that kind.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic