Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try/catch blocks inside constructors

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

like image 474
Shamika Avatar asked Feb 18 '10 03:02

Shamika


People also ask

Can we use try catch block in constructor?

Yes, we can write try catch and finally block in a constructor ant it works properly.

Can constructor have try catch in Java?

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.

Can we have try catch block inside catch block?

Yes, we can declare a try-catch block within another try-catch block, this is called nested try-catch block.

Is it OK to have nested try catch?

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.


1 Answers

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.

like image 93
Adam Robinson Avatar answered Sep 29 '22 00:09

Adam Robinson