请参阅以下示例代码:
try
{
string str = MyMethod();
}
catch
{
}
public string MyMethod()
{
CookieContainer cookieJar = new CookieContainer();
... -> Some Codes That Make An Exception
}
如何将cookieJar传递给Catch方法?
提前致谢
答案 0 :(得分:3)
你做了一个新的
public class CookieJarException : Exception
{
public CookieJar Jar {get; private set;}
public CookieJarException(CookieJar a)
{
Jar = a;
}
}
然后你
throw new CookieJarException(cookieJar);
答案 1 :(得分:1)
将其作为全局变量。
通过定义您自己的异常类,该异常类继承自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
}
}
}