Win a copy of Head First Android this week in the Android forum!
  • 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:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

Does "catch" AND "declare" generate a complilation error?

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If a checked exception is thrown in the catch block, it MUST also be declared. If a checked exception is thrown inside a method, it must EITHER be caught in a try catch block OR declared. But what happens if we both declare AND catch a checked exception(thrown in a try block and caught in a matching catch block)? Does it generate a compilation error? Should the methods calling the present method declare/catch the exception thrown in the present method?
 
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The catch block will run it. For this case, the throws declaration is for rethrowing the checked exception in catch block again.
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The best way to verify this is to write some code and experiment with it. But note that declaring an exception simply indicates that an exception might be thrown -- there is no requirement to actually throw one. So if it ends up being caught...
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
But be aware that for checked exceptions, the compiler will pay attention to whether they are caught or not (that's what the "checked " means after all). If you declare a checked exception, and the compiler can tell that the exception is definitely caught and not rethrown, then the compiler will complain that you've declared a checked exception which is not thrown.

Note that for unchecked exceptions, none of this applies. You can catch them or declare them, both or neither. You're on your own; the compiler doesn't care.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic