File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes main() throws, who catches? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "main() throws, who catches?" Watch "main() throws, who catches?" New topic

main() throws, who catches?

David Duran
Ranch Hand

Joined: Feb 11, 2002
Posts: 122
If I've got a main functions that throws some a generic exception, who catches it?

FileInputStream throws a FileNotFoundException but the program doesn't complain because main declares that it throws Exception. Of course, if I remove "throws Exception" then it says I need to catch the FileNotFoundException.
So if main throws the Exception, where is it being caught?
Rob Ross

Joined: Jan 07, 2002
Posts: 2205
When there is no handler for an exception and it has propagated all the way up the calling stack, the thread in which it is thrown will be killed, and the ThreadGroup of which that thread is a member will handle the error. In your case, the main ThreadGroup catches the error and writes it to System.err, then the main thread dies; thus your program ends.
If you wanted to see how this works in another thread, just run your error-producing code in another thread. That thread will die, but your main will continue.

SCJP 1.4
I agree. Here's the link:
subject: main() throws, who catches?
It's not a secret anymore!