wood burning stoves 2.0*
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 Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "throwing exceptions" Watch "throwing exceptions" New topic
Author

throwing exceptions

sin sai
Greenhorn

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

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
Greenhorn

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.
Kevin


SCJP, SCJD<p>MindBeans Software Consulting<br /><a href="http://www.mindbeans.net" target="_blank" rel="nofollow">http://www.mindbeans.net</a><p>Kev's Development Toolbox<br /><a href="http://www.kevinhooke.com" target="_blank" rel="nofollow">http://www.kevinhooke.com</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: http://aspose.com/file-tools
 
subject: throwing exceptions
 
Similar Threads
Overiding with Exceptions
main() throws, who catches?
Catching Exceptions...
OCPJP 6 Practice exams, exam 2 q 29 error
Exception