• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Declaring Exceptions in main()

 
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I read from the study guide that every method should declare or handle the Exception it might throw.Can we neither declare nor handle exceptions in main() method?..Then why does the following code compile


Here main() calls s1() which throws an Exception.The book says the output is -c ....but I think it should be compilation error...please tell me where I went wrong...Thanks in advance
 
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
as far as i have got your question you want to modify main.but main is calling only s1 which handles the exception which may be thrown by s2.If s1 were not catching the Exception only declaring it (as throws Exception instead of present try catch block) yuu have to handle or declare it in main.
 
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Look at your code again. s1 does not throw a checked exception. It catches a checked exception from s2 and does not re-throw it.

Having said that, in general, you can declare main to throw checked exceptions. And, of course, you can definitely catch and handle exceptions within main as well.
 
Sugantha Jeevankumar
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So...does that mean if the methods below a particular method in the stack trace have already handled the Exception using a try/catch block then there is no need to handle or declare the Exception 'In' the method?

a() //need not handle or declare ??
b() //handles it with try/catch
c() //rethrows it
d() //throws an Exception
 
Prahlad Joshi
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
yes unless the catch block itself throws an Excption
 
reply
    Bookmark Topic Watch Topic
  • New Topic