在C#中,捕获对象的新初始化块内的异常。

huangapple go评论71阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月22日 03:58:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76526735.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定