Win a copy of Escape Velocity: Better Metrics for Agile Teams this week in the Agile and Other Processes 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:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

Problem with wrapping a method in try/catch block

 
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator



If i replace YYY s =new YYY();
with
XXX s =new YYY();
then why is it necessary to wrap the main method in try/catch block . The s.m() will call the method m from class YYY, which does not throw any exception.So it shouldn't be necessary to wrap it in a try/catch block.
 
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The compiler only knows and cares about the reference type (which is fixed at compile time), not the object class (which can be determined at runtime).

That is, it only cares about XXX s, not about =new YYY(), and since XXX.m() is declared to throw Exception, you have to deal with it.

So, yes, is should be (and is) necessary to catch or declare Exception. Whenever the compiler or the runtime does X, and you find your self thinking, "It should be doing the opposite of X," it's time to reevaluate your assumptions.
 
Rohan Deshmkh
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
OK thanks, got it.
 
Acetylsalicylic acid is aspirin. This could be handy too:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic