A question about exceptions
Posted: Wed Jun 06, 2012 4:55 am
Sorry for the long post But I'm really confused with Exceptions, I noticed that sometimes when an exception occurs in a method, the method has to declare that it throws this exception. And sometimes it's not necessary to declare that it throws this Exception. I noticed that it depends on the exception itself. example:
class A {
public void doA() { throw new Exception("Exception"); }
public static void main(String[] args) {
A a = new A();
try{
a.doA();}
catch(Exception e){ }
}
}
This code fails to compile because there is unreported Exception. But if I changed the Exception to NullPointerException then it will compile as in:
class A {
public void doA() { throw new NullPointerException("Exception");}
public static void main(String[] args) {
A a = new A();
try{
a.doA();}
catch(Exception e){ }
}
}
So what kind of exceptions that require method to declare that it throws exceptions?
Thanks for your time
class A {
public void doA() { throw new Exception("Exception"); }
public static void main(String[] args) {
A a = new A();
try{
a.doA();}
catch(Exception e){ }
}
}
This code fails to compile because there is unreported Exception. But if I changed the Exception to NullPointerException then it will compile as in:
class A {
public void doA() { throw new NullPointerException("Exception");}
public static void main(String[] args) {
A a = new A();
try{
a.doA();}
catch(Exception e){ }
}
}
So what kind of exceptions that require method to declare that it throws exceptions?
Thanks for your time