• Post Reply Bookmark Topic Watch Topic
  • New Topic

Exception/variable question  RSS feed

 
Emnaki Chih
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Here is my question, ClassA throws an uncaught exception in its constructor, so I have to catch an exception everytime I create a ClassA object. In the method transpose I would like to handle the exception instead of throwing it because I want to get it to match an interface. My compiler gives the error that the variable mat is not recognised, probably because it is in the try section. But I can't create a ClassA object without a try statement! I really hope you understand what I mean. So is what I want to do even possible? Is there a better design I could use?
 
Moritz Petersen
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem with throwing exceptions in the constructor is, that if the exception is thrown, the instance is not yet created. The only choice you have is to return a default instance or null. However, usually exceptions have their reason, which should not just be ignored. So probably you should actually deal with the exception instead of ignoring it.

If you can say for sure, that the Exception will never happen -- and only a dumbass programmer added the throws clause to the constructor --, then I would suggest the following pattern:



or



Hope that helps.
-Mo.

[ April 28, 2005: Message edited by: Moritz Petersen ]
[ April 28, 2005: Message edited by: Moritz Petersen ]
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!