Where do Java exceptions came from?

Until now, I thought that every Java exception has to be created somewhere by a constructor, as I can create on my own, custom exceptions:

throw new Exception();

But now it seems that I have to handle some exception from JavaMail - MessagingException. It comes from the method Store.close (inherited from Service class).

I went there (I need to check when this exception is thrown so I know what can be wrong) and I see that this method calls two other methods - none of them throw an exception!

public synchronized void close() throws MessagingException {

As far as I understand, this is checked Exception (neither Error nor RuntimeException), so how is it possible that it doesn't have to be declared in any of used by close method commands? It is also not created here, in this method.

Jon Skeet

The exception being declared isn't about what that implementation can throw - it's about what that implementation or the implementation in subclasses can throw. Service is an abstract class - and so are the two direct subclasses implemented by JavaMail (Transport and Store). Even if neither of those overrides close(), it's still entirely possible that the concrete implementation you use may override close() and its implementation may throw MessagingException.

Does it make sense from an API design viewpoint? I'd have to look more closely at JavaMail to be any kind of judge of that, and thankfully I haven't had to use JavaMail for a long time.

Does it makes sense from a language viewpoint? Absolutely. It's entirely reasonable to have an implementation which doesn't throw a particular checked exception, but anticipates that concrete subclasses may need to.


See more on this question at Stackoverflow