File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

throwing exceptions

 
sin sai
Greenhorn
Posts: 10
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when "main method" throws an exception, where is the exception thrown to and who catches the exception?
example:

sin sai
 
Jeff Bosch
Ranch Hand
Posts: 805
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Kevin Hooke
Greenhorn
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jeff Bosch
Ranch Hand
Posts: 805
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1090
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 805
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic