C# - 如何在 try catch 块中使用未分配的变量

发布于 2024-12-07 14:57:43 字数 699 浏览 0 评论 0原文

crmFactory.RegisterDemoAccount 抛出 Exception。为了使用变量 res,我需要初始化它。

由于 AccountRegistrationResponse 不可初始化,如何声明 res 而不会出现有关使用未分配变量的编译错误? 我可以将其分配为 null,但我认为这不是一个好的编程方法。

AccountRegistrationResponse res /*=null*/; 
 try
 {
  res = crmFactory.RegisterDemoAccount(CrmConfigRepository.CrmOwnerUserId
                                   , CrmConfigRepository.CrmOrganizationName
                                   , CrmConfigRepository.CrmBusinessUnitName
                                   , demo.getData());
 }
 catch (Exception e)
 {
      _log.Error("Cannot create demo account", e);
 }
 _log.Debug(res.getString());

crmFactory.RegisterDemoAccount throws Exception. In order to use the variable res I need to initialize it.

Since AccountRegistrationResponse is not initializable, how can I declare res without getting compilation errors about using unassigned variables?
I can assign it to null, but I don't think this is a good programming approach.

AccountRegistrationResponse res /*=null*/; 
 try
 {
  res = crmFactory.RegisterDemoAccount(CrmConfigRepository.CrmOwnerUserId
                                   , CrmConfigRepository.CrmOrganizationName
                                   , CrmConfigRepository.CrmBusinessUnitName
                                   , demo.getData());
 }
 catch (Exception e)
 {
      _log.Error("Cannot create demo account", e);
 }
 _log.Debug(res.getString());

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

一花一树开 2024-12-14 14:57:43

您不应该在捕获未知异常后尝试继续您的方法。任何事情都可能出错,假设继续安全是没有意义的。如果你尝试的话,只会发生不好的事情。

要么返回错误结果,要么更好,只是重新抛出原始异常:

 catch (Exception e)
 {
      _log.Error("Cannot create demo account", e);
      throw;
 }

现在编译器可以看到,在 try 块成功完成后,res 始终会被赋值。

You shouldn't try to continue your method after catching an unknown exception. Anything could have gone wrong and it makes no sense to assume that it's safe to continue. Only bad things can happen if you try.

Either return an error result, or better, just rethrow the original exception:

 catch (Exception e)
 {
      _log.Error("Cannot create demo account", e);
      throw;
 }

Now the compiler can see that res will always be assigned after the try block completes successfully.

み零 2024-12-14 14:57:43

我理解您不愿意将 res 分配给 null - 这感觉毫无意义,因此是错误的。不过,当在分配对象的块之外需要对象时,这是这种情况下的常见方法。假设您在 try/catch 块中分配变量时做了正确的事情(在许多情况下,这不是一种不常见的模式),我不会担心它。

但是,如果任务失败了怎么办?第二个日志记录调用将尝试取消引用 res,并抛出 NullReferenceException。那不好。

I understand your reluctance to assign res to null - it feels pointless, and therefore wrong. It is a common approach in situations like this, though, when an object is needed outside the block in which it's assigned. Assuming you're doing the right thing in assigning your variable in a try/catch block (and it's not an uncommon pattern, in many cases), I wouldn't worry about it.

However, what would happen if the assignment failed? The second logging call would try to dereference res, and throw a NullReferenceException. That's not good.

你曾走过我的故事 2024-12-14 14:57:43

您需要将日志行放在 try/catch 中,以便编译器知道 res 已初始化。

try
{
    res = ...
    _log.Debug(res.getString()); }
catch (Exception e)
{
    _log.Error("Cannot create demo account", e);
}

You need to put the logging line inside the try/catch so that the compiler knows that res has been initialised.

try
{
    res = ...
    _log.Debug(res.getString()); }
catch (Exception e)
{
    _log.Error("Cannot create demo account", e);
}
嘦怹 2024-12-14 14:57:43

这是正确的方法。唯一的事情是,如果 nullRegisterDemoAccount 的有效返回值,您可以添加一个设置为 true 的 boolinitialized = false 就在 RegisterDemoAccount 之后。

It's THE right approach. Only thing, if null is a valid return value of RegisterDemoAccount, you could add a bool initialized = false that you set to true just after the RegisterDemoAccount.

ぺ禁宫浮华殁 2024-12-14 14:57:43

正如您所说,如果您在 try/catch 之外需要它,请将其分配为 null。这不是一个坏的编程方式。

Assign it to null, like you said, if you need it outside of try/catch. It's not bad way of programming.

祁梦 2024-12-14 14:57:43

但我认为这不是一个好的编程方法。

为什么?如果您没有初始化 res,然后 RegisterDemoAccount(...) (或其之前的另一个表达式)抛出异常,则 res 将不会被分配在 try 语句中。

因此,执行可能会在 res 未分配的情况下到达最终语句(在 catch 块之后)。

问题是在最后一个语句中使用了 res - 编译器可以看到它可以在没有初始化的情况下达到这一点。

but I don't think this is a good programming approach.

Why? If you don't initialise res and then RegisterDemoAccount(...) (or another expression before it) throws then res will not be assigned in the try statement.

Therefore execution could reach the final statement (after the catch block) with res unassigned.

The problem is the use of res in that last statement – the compiler can see it can get to this point without initialisation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文