开发者

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

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.

AccountRegist开发者_开发技巧rationResponse 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.


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.


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);
}


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.


Assign it to null, like you said, if you need it outside of 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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜