如何从另一个方法返回catch [英] How to return catch from another method
本文介绍了如何从另一个方法返回catch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望能够将我的IsValidEmailDomain方法中的错误捕获到我的test方法中。这有可能实现吗?
I would like to be able catch error from my "IsValidEmailDomain" method into my "test" method. Is this possible to achieve?
public static bool IsValidEmailDomain(MailAddress address)
{
if (address == null) return false;
var response = DnsClient.Default.Resolve(address.Host, RecordType.Mx);
try
{
if (response == null || response.AnswerRecords == null) return false;
}
catch (FormatException ex)
{
ex.ToString();
throw ex;
//return false;
}
return response.AnswerRecords.OfType<MxRecord>().Any();
}
public static bool IsValidEmailDomain(string address)
{
if (string.IsNullOrWhiteSpace(address)) return false;
MailAddress theAddress;
try
{
theAddress = new MailAddress(address);
}
catch (FormatException)
{
return false;
}
return IsValidEmailDomain(theAddress);
}
public static string test()
{
string mail = "########";
string error = "notValid";
if (IsValidEmailDomain(mail))
{
return mail;
}
else
{
///How to return catch from IsValidEmailDomain() method.
}
}
任何提示都会有所帮助。感谢您的时间和帮助。
Any hints would be most helpful. Thank you for your time and help.
推荐答案
您可以将方法更改为:
You can change your method to:
public static bool IsValidEmailDomain(MailAddress address, out Exception exception)
{
exception = null;
....
// and in case of errors, before return assign it:
catch (FormatException ex)
{
exception = ex.ToString();
throw ex;
//return false;
}
.....
在调用函数中使用异常如下: />
The use the exception in the calling function like this:
public static string test()
{
string mail = "########";
string error = "notValid";
Exception exception = null;
if (IsValidEmailDomain(mail, out exception))
{
return mail;
}
else
{
///How to return catch from IsValidEmailDomain() method.
exception.ToString();
// Use the exception as you like...
}
}
这篇关于如何从另一个方法返回catch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文