Error handling in constructor

This is a discussion on Error handling in constructor within the C# Programming forums, part of the General Programming Boards category; I wonder what general strategy one should have when it comes to error handling in constructors. How do you do? ...

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    41

    Error handling in constructor

    I wonder what general strategy one should have when it comes to error handling in constructors. How do you do? Do whatever you can to avoid that it happens, that is only call the constructor with working range values.
    Or do you throw exceptions and have a thorough handling of that.

    I'm hesitating abit on how to approach it.

  2. #2
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    In general it's ok to throw exceptions from the constructor, several of the standard .NET classes does it.
    You may want to be careful that you always release unamanged resources you have allocated though in case of an exception.
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  3. #3
    Registered User
    Join Date
    Nov 2005
    Posts
    41
    Thanks

  4. #4
    Registered User
    Join Date
    Apr 2008
    Location
    USA
    Posts
    22

    Thumbs up

    It is good practice to use error handling in constructors for anything and everything as you can not ensure the integrity of a resource. This prevents your system from crashing if a bad or poorly designed resource is opened with your application.

    Excellent question.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 06-10-2008, 08:38 PM
  2. C++ have a constructor call another constructor
    By QuestionC in forum C++ Programming
    Replies: 4
    Last Post: 05-17-2007, 01:59 AM
  3. Replies: 3
    Last Post: 03-25-2006, 11:59 PM
  4. How do I override constructor in inheritance?
    By Loduwijk in forum C++ Programming
    Replies: 13
    Last Post: 03-24-2006, 08:36 AM
  5. Need help in classes
    By LBY in forum C++ Programming
    Replies: 11
    Last Post: 11-26-2004, 03:50 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21