简体   繁体   English

我如何在C#中将变量从方法发送到该调用者方法的catch块?

[英]How can i send a variable from a method to the catch block of that caller's method in c#?

Let's say I have a method like this. 假设我有一个这样的方法。

Boolean hasErrors = false;
try
{
    var anotherId = DoSomethingWithList(list);
}
catch (Exception ex)
{
    errorMessageDetail.Text = ex.Message;
    hasErrors = true;
}

And In my DoSomethingWithList method I am doing fancy stuff in an iteration. 在我的DoSomethingWithList方法中,我在迭代中做一些花哨的东西。

public Guid? DoSomethingWithList(List<ofthings> myList)
{
    foreach (var member in myList)
    {
          //Do fancy and dangerous stuff in here.
    }
}

What I try to achieve is that, When I get an exception in DoSomethingWithList method I also want to know in which member of the list this exception has been thrown, and include it in errorMessageDetail . 我试图实现的目标是,当我在DoSomethingWithList方法中获得异常时,我还想知道该异常在列表的哪个成员中引发,并将其包含在errorMessageDetail Thank you in advance. 先感谢您。

Edit: I can not simply move my exception block into the loop itself because errorMessageDetail is connected with the aspx in the front end, and my DoSomethingWithList method is in my Business Layer. 编辑:我不能简单地将异常块移入循环本身,因为errorMessageDetail与前端的aspx连接,而我的DoSomethingWithList方法位于我的业务层中。

You could create your specific exception type. 您可以创建特定的异常类型。 Eg 例如

public Guid? DoSomethingWithList(List<ofthings> myList)
{
    foreach (var member in myList)
    {
        try
        {
          //Do fancy and dangerous stuff in here.
        }
        catch (Exception ex)
        {
             throw new ListProcessingException(member, ex);
        }
    }
}

Try this. 尝试这个。

public Guid? DoSomethingWithList(List<ofthings> myList){
foreach (var member in myList){
    try{
      //Do fancy and dangerous stuff in here.
    }
    catch(Exception e){
        throw new Exception(string.Format("{0} thrown by {1}", e.Message, member.ToString()), e);    
    }
}

I'm assuming member has a suitable implementation of ToString(), otherwise just use whatever property is relevant. 我假设成员具有ToString()的适当实现,否则只需使用任何相关属性即可。

the only way to return state from DoSomethingWithList in case of error is to wrap its functionality in another try catch as @Stefan Steinegger said. 如果发生错误,从DoSomethingWithList返回状态的唯一方法是将其功能包装在另一个try catch中,如@Stefan Steinegger所说。

because if you dont catch the exception the (thread / callstack) will be killed and thus stack frames will be dead. 因为如果您没有捕获到该异常,则(线程/调用堆栈)将被杀死,因此堆栈帧将失效。 (stack frame is where locals are stored) (堆栈帧是本地人存储的位置)

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

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