Try/catch blocks inside constructors

12,798

System.TypeInitializationException is thrown when a static constructor throws an exception, not on an instance constructor. Exceptions are thrown normally in instance constructors.

That aside, there's nothing "wrong" with it any more than it is anywhere else; handle exceptions that you can properly recover from, and allow those that you can't to bubble up.

Share:
12,798
Shamika
Author by

Shamika

Updated on August 18, 2022

Comments

  • Shamika
    Shamika over 1 year

    Is it a bad programming practice to have try/catch blocks inside constructors? Or does it make no difference as long as our programs handle typeinitializer exceptions gracefully.

    In C# if there are any exceptions inside a constructor the framework always throws typeinitilizer exceptions.

    Thanks, Shamika

  • Shamika
    Shamika about 14 years
    Thanks for the explanation on System.TypeInitializationException and yes, in my case it's a static constructor indeed.
  • Adam Robinson
    Adam Robinson about 14 years
    @Shamika: Nonetheless, the same answer applies; if you can recover from the exception, then catch it. If you can't, then don't. Also note that exceptions encountered in static member initialization can't be caught (they will throw a TypeInitializationException).
  • John Demetriou
    John Demetriou over 7 years
    question, is it better to use a try catch surrounding the call to the constructor or inside the constructor?
  • Adam Robinson
    Adam Robinson over 7 years
    @JohnDemetriou As with exceptions in general, you should catch an exception only when you can handle the exception (unless you rethrow). If your constructor can complete and give you a valid object in the event of that exception, then you should have the try-catch in the constructor. If not, then don't put it in there unless you rethrow it.