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
Yes, we can write try catch and finally block in a constructor ant it works properly.
Yes, it is very much possible to throw exception in constructor. Usually, In constructors code will be written for initialization, there is a possibility of exceptions taking place while initializing. So there is no specific reason why exceptions cannot be thrown in a constructor.
Yes, we can declare a try-catch block within another try-catch block, this is called nested try-catch block.
Nesting try-catch blocks severely impacts the readability of source code because it makes it to difficult to understand which block will catch which exception.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With