2016-02-12 95 views
1

我在userinfo表中有一些用户信息,如果代码执行失败意味着控制将会捕获块,我可以在catchy块中返回什么。在catch块中返回什么

public static UsersInfo GetById(int Userid) 
    { 
     if (Userid <= null) 
     { 
      throw new ArgumentNullException(); 
     } 
     try 
     { 
      UnitOfWork unitofwork = new UnitOfWork(); 
      var user = unitofwork.UserInfoRepository.GetByID(Userid); 
      return user; 
     } 
     catch(Exception ex) 
     { 
     // What to return in catch block ? 

     } 

    } 
+0

那么,在这种情况下,它已经到了要返回的东西了。您可以根据您的需要返回'null'或者'UsersInfo'的某种填充实例作为“默认”值。 –

+0

你想从'catch'返回什么? – Dennis

+0

这取决于你想要的。您可以向呼叫者抛出异常,以便呼叫者知道呼叫有什么问题。在投掷之前,您可能需要记录异常以便以后进行故障排除和分析。如果调用者不需要知道错误,那么你可以返回null。 – Adil

回答

0

你必须可以实现什么不同的选项(所以它的你来决定

选项1:当你的代码进入catch块像

可以抛出一个异常
catch (Exception ex) 
{ 
    throw new SomeException(ex); 
} 

选项2:您可以为您的用户恢复默认值像

catch(Exception ex) 
{ 
    return "some value"; 
} 

方案3:您可以显示显示异常的消息像

catch(Exception ex) 
{ 
    MessageBox.Show(ex.message); 
    return "some value or empty string"; 
} 
+2

选项3不是一个好的设计决策。它不遵守“关注点分离”/“单一责任原则”,从而使得代码不易重用。 – Amit

+2

选项4.如果这不是您业务逻辑的要求,您可以抛弃'catch'并且根本不捕获异常(尤其是'Exception')。 – Dennis

+0

@Amit: - 同意,我只是给了一个选项,希望OP会决定在她/他的代码中选择哪一个。 –

1

通过问这个问题,你的暗示GetById对如何处理异常不“业务定义”。在这种情况下,它不应该担心它,只需让调用方处理业务逻辑确实知道该怎么做的例外。

例如,如果调用者是用户要求获取某些用户的详细信息的某个用户界面启动的过程,则可能会显示失败消息。

1

IMO,您应该在打印堆栈跟踪后再次抛出异常。我的意思是,如果一个异常被抛出此代码:

UnitOfWork unitofwork = new UnitOfWork(); 
    var user = unitofwork.UserInfoRepository.GetByID(Userid); 

有可能出错了Userid。如果该参数是无效的,抛出一个InvalidArgumentException

catch (Exception ex) { 
    // Do something with ex here, probably print the stack trace 
    throw new InvalidArgumentException("There's something wrong with Userid!"); 
} 

虽然这可能会导致您的应用程序崩溃了很多,这是更好地知道哪里出了问题。

或者,您可以返回特殊值UsersInfo。我会建议null或添加名为Error的属性。

public string Error { 
    get; set; 
} 

您可以检查此字符串是否有错误消息。这里有一个例子:

var info = GetById(10); 
if (info.Error != null) { 
    Console.WriteLine("Oops! Some error occurred when retrieving user info:"); 
    Console.WriteLine(info.Error); 
    // Do some other handling here. 
} 

也可以使ExceptionError呢!

+0

@Seeper谢谢。现在我得到了一些清晰的图片 –

+0

如果您认为可以回答您的问题,请考虑通过点击该节点来接受它! @SrinivasR – Sweeper

1

追赶所有的不throw东西回来就是非常不好的做法例外;想象一下unitofwork.UserInfoRepository已经抛出,比如OutOfMemoryException - 你还想继续吗?

public static UsersInfo GetById(int UserId) { 
    // int is a struct, it can't be null 
    // be exact: what's wrong? - "UserId"; why? - it's non-positive 
    if (UserId <= 0) 
     throw new ArgumentOutOfRangeException("UserId", "Non-positive UserId is not allowed"); 

    try { 
     return new UnitOfWork().UserInfoRepository.GetByID(UserId); 
    } 
    catch (SomeDistinctException) { //TODO: put the right exception type here 
     return null; // UserInfo is not found 
    } 
    } 
+0

非常感谢你@Dmitry这就是我期待的:) –