英文:
catch exception inside new initialized blocked of an object in c#
问题
我无法在使用关键字"new"创建的对象的简化初始化块内捕获异常。
Test test1 = new Test() { };
我尝试了下面的代码,但无法捕获异常。
Test test1 = new Test()
{
try
{
}
catch()
{
}
};
英文:
Here I am unbale to catch the exception inside the simplified initialized block of an object created using new keyword.
Test test1 = new Test() { };
I tried below code but unbale to catch the exceptions
Test test1 = new Test()
{
try
{
}
catch()
{
}
};
答案1
得分: 2
{ }
在这里是一个对象初始化器,而不是一段代码块:
Test test1 = new Test() { };
你不能在对象初始化器中随意放置任何语句。它只是用于初始化新创建对象的属性的语法。例如:
Test test1 = new Test() { SomeProperty = "test" };
在大多数情况下,它在语义上与以下代码几乎相似:
Test test1 = new Test();
test1.SomeProperty = "test";
如果你想捕获在对象创建过程中发生的异常,可以将其包装在 try/catch 块中。例如:
try
{
Test test1 = new Test() { SomeProperty = "test" };
// 使用 test1 做一些操作...
}
catch (Exception ex)
{
// 处理异常
}
或者,如果 test1
的作用域需要在 try/catch 外部,你可以先 声明 它:
Test test1 = null;
try
{
test1 = new Test() { SomeProperty = "test" };
}
catch (Exception ex)
{
// 处理异常
}
// 如果 test1 不为 null,则使用它进行操作...
另一方面,如果你希望在给定属性的 setter 中更具体地处理异常,你可以在该 setter 中处理它们,或者避免使用对象初始化器语法,逐个设置属性,根据需要为你的逻辑包装相关属性的 try/catch 块。
英文:
The { }
here is an object initializer, not a block of code:
Test test1 = new Test() { };
You can't just put any statements you like in an object initializer. It's just syntax for initializing properties on the newly created object. For example:
Test test1 = new Test() { SomeProperty = "test" };
It's semantically similar (similar enough in nearly all cases) to this:
Test test1 = new Test();
test1.SomeProperty = "test";
If you want to catch an exception which occurs during the creation of the object, wrap it in a try/catch. For example:
try
{
Test test1 = new Test() { SomeProperty = "test" };
// use test1 for something...
}
catch (Exception ex)
{
// handle the exception
}
Alternatively, if the scope of test1
needs to be outside of the try/catch, you can declare it first:
Test test1 = null;
try
{
test1 = new Test() { SomeProperty = "test" };
}
catch (Exception ex)
{
// handle the exception
}
// if test1 is not null, use it for something...
If, on the other hand, you're looking to handle exceptions more specifically within the setters for any given property, you'd either handle them within that setter or you'd avoid the object initializer syntax and individually set the properties, wrapping relevant ones in a try/catch as needed for your logic.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论