Saturday, 10 November 2012

When to declare "throws Exception"


 
In Java, when defining a method, we also need to declare in the method head what exception may be throw. That's what I was believing, but, in my instructor's slides, some methods she did this way, some methods she just throw exception right the way. such as following:
public void methodA() throws AnException {   
 //do something    throw new AnException();
}
public void methodA() {  
 //do the same thing    throw new AnException();
}

And I am kind of confusing in which situation we need to declare, 
is there a specific requirement or restriction? or we can do it either way depends
on our mood?
after some google, I find that there are two different major type of exceptions, 
one is checked, which does not extend RuntimeException, and those exceptions must
be declared. In the other hand, unchecked exception is the exception that extends
RuntimeException, and then either way is allowed(declare/not declare). But now I have other doubts like, in which circumstances our exception should extends RuntimeException?
what is the difference between those two? and what is the advantage on each?

No comments:

Post a Comment