如何从OutSide try / catch传递一些值来捕获方法

时间:2012-10-13 13:51:54

标签: c# visual-studio-2010 methods parameters try-catch

请参阅以下示例代码:

try
{
      string str = MyMethod();
}
catch
{

}
public string MyMethod()
{
     CookieContainer cookieJar = new CookieContainer();
     ... -> Some Codes That Make An Exception
}

如何将cookieJar传递给Catch方法?

提前致谢

3 个答案:

答案 0 :(得分:3)

你做了一个新的

public class CookieJarException : Exception
    {
        public CookieJar Jar {get; private set;}

        public CookieJarException(CookieJar a)
        {
            Jar = a;
        }

    }

然后你

throw new CookieJarException(cookieJar);

答案 1 :(得分:1)

  1. 将其作为全局变量。

  2. 通过定义您自己的异常类,该异常类继承自System.Exception并具有要保留cookieJar的属性。然后,try/catch中的MyMethod()会抓住任何异常并提升CookieLovingException,而设置属性和InnerException。 然后外部处理程序将catch CookieLovingException ex

答案 2 :(得分:-2)

你可以在这里使用finally块。终于总是执行

        public string MyMethod()
        {
            CookieContainer cookieJar = new CookieContainer();
            try
            {

                // Some Codes That Make An Exception
                string str = MyMethod();
            }
            catch (Exception)
            {
                 if (cookieJar != null)
                {
                    // do whatever u want
                }
            }
            finally
            {
                if (cookieJar != null)
                {
                    // do whatever u want
                }
            }
        }