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 throwing exceptions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "throwing exceptions" Watch "throwing exceptions" New topic

throwing exceptions

sin sai

Joined: Jun 19, 2002
Posts: 10
when "main method" throws an exception, where is the exception thrown to and who catches the exception?

sin sai

sin sai
Jeff Bosch
Ranch Hand

Joined: Jul 30, 2003
Posts: 804
I don't believe you can catch that exception.
To catch an exception, you need a try-catch block, which must be declared inside a method. The JVM calls main(), not another class, so where could you put try-catch? I guess, technically, the JVM would "catch" the exception by terminating your program and printing a stack trace, but it would do that anyway, so why type the extra code?
The declaration is legal, but I don't think it's particularly useful.

Give a man a fish, he'll eat for one day. Teach a man to fish, he'll drink all your beer.
Cheers, Jeff (SCJP 1.4, SCJD in progress, if you can call that progress...)
Kevin Hooke

Joined: Aug 21, 2003
Posts: 1
It will be uncaught, and like Jeff said, the JVM will terminate your application. If you don't want this to happen, then you should catch any exceptions you are expecting within the main() method and handle them appropriately, to avoid your app abnormally ending.

SCJP, SCJD<p>MindBeans Software Consulting<br /><a href="" target="_blank" rel="nofollow"></a><p>Kev's Development Toolbox<br /><a href="" target="_blank" rel="nofollow"></a>
Jeff Bosch
Ranch Hand

Joined: Jul 30, 2003
Posts: 804
Thanks, Kevin. I was thinking of having main() inside a try-catch, which would be illegal. I think you're saying that the code could be modified to something like:

Now you're catching the exception, printing a stack trace, but not terminating the program.
Anupam Sinha
Ranch Hand

Joined: Apr 13, 2003
Posts: 1088
Hi Sin
Using throws in the main() method may be useful in case you yourself would like to call main() from your program. As in the program. But I guess that this approach is hardly used.
Jeff Bosch
Ranch Hand

Joined: Jul 30, 2003
Posts: 804
There is another possibility if you really need to catch Exception from main(): Have only one method call in main(), say, to doMainStuff().

It's not pretty, but I think it would accomplish what Sin Sai seemed to be trying to do.
I agree. Here's the link:
subject: throwing exceptions
Similar Threads
Overiding with Exceptions
Catching Exceptions...
main() throws, who catches?
OCPJP 6 Practice exams, exam 2 q 29 error