Possible Duplicate:
The throws keyword for exceptions in Java
In Java, a lot of method are ended with throws Exception. Why it is neccessary to add this?
Possible Duplicate:
The throws keyword for exceptions in Java
In Java, a lot of method are ended with throws Exception. Why it is neccessary to add this?
It's generally considered that methods that throws Exception
is a bad idea. The reason being that it gives no clues to the calling code as to what category of exceptions they might be expected to handle. Therefore seeing throws Exception
is usually the sign of either poorly designed code or lazy developers.
The recommended practices are to either handle the exceptions generated or to throw explicit exceptions that give more context. For example, from the JDK, java.io.IOException is a commonly thrown exception which to some degree is still general, but at least gives you an idea of what sort of error occurred.
You should only add a throws Exception
if you have no other choice.
I assume that you really mean "... a lot of method are ended with throws SomeException
" ... where SomeException
is some exception name.
The answer is that the Java language requires a method to list all checked exceptions that may be thrown in a method or some other method that it calls. This is how you do it.
As @Derek Clarkson notes, declaring a method as throwing Exception
is bad practice. Since Exception
is a checked exception, the calling method is forced to deal with it. And you are declaring that any exception is possible, so how can it deal with that in any sensible fashion.
Best practice is to only declare checked exceptions that are actually going to be thrown.