在构造函数中尝试/ catch块 [英] Try/catch blocks inside constructors
问题描述
在构造函数中有try / catch块是一个糟糕的编程习惯吗?或者它没有什么区别只要我们的程序处理typeinitializer异常优雅。
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.
在C#中,如果构造函数中存在任何异常,框架总是抛出类型异常。
In C# if there are any exceptions inside a constructor the framework always throws typeinitilizer exceptions.
b $ b Shamika
Thanks, Shamika
推荐答案
System.TypeInitializationException
em> static 构造函数抛出异常,而不是实例构造函数。
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.
这篇关于在构造函数中尝试/ catch块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!