简体   繁体   English

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

[英]C# - How to use unassigned variable in try catch block

crmFactory.RegisterDemoAccount throws Exception . crmFactory.RegisterDemoAccount抛出Exception In order to use the variable res I need to initialize it. 为了使用变量res我需要对其进行初始化。

Since AccountRegistrationResponse is not initializable, how can I declare res without getting compilation errors about using unassigned variables? 由于AccountRegistrationResponse无法初始化,如何在不使用未分配变量的编译错误的情况下声明res I can assign it to null, but I don't think this is a good programming approach. 我可以将其分配为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());

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. 现在,编译器可以看到,在try块成功完成之后,将始终分配res

I understand your reluctance to assign res to null - it feels pointless, and therefore wrong. 我了解您不愿意将res分配为res感觉毫无意义,因此是错误的。 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. 假设您在try / catch块中分配变量时做得正确(在很多情况下,这不是一种罕见的模式),那么我不必担心。

However, what would happen if the assignment failed? 但是,如果分配失败会怎样? The second logging call would try to dereference res , and throw a NullReferenceException . 第二个日志记录调用将尝试取消对res引用,并抛出NullReferenceException That's not good. 这不好。

You need to put the logging line inside the try/catch so that the compiler knows that res has been initialised. 您需要将日志记录行放在try / catch中,以便编译器知道res已经初始化。

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

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 . 唯一的事情,如果null是一个有效的返回值RegisterDemoAccount ,你可以添加一个bool initialized = false ,你设置为true刚后RegisterDemoAccount

Assign it to null, like you said, if you need it outside of try/catch. 如您所说,将其分配为null,如果您需要在try / catch之外使用它。 It's not bad way of programming. 这是不错的编程方式。

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. 如果不初始化res ,然后抛出RegisterDemoAccount(...) (或之前的其他表达式),则try语句中不会分配res

Therefore execution could reach the final statement (after the catch block) with res unassigned. 因此,执行可以到达未声明res的最终语句(在catch块之后)。

The problem is the use of res in that last statement – the compiler can see it can get to this point without initialisation. 问题是在最后一条语句中使用了res –编译器可以看到无需初始化即可达到目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM