Click here to Skip to main content
15,905,238 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I would like to be able catch error from my "IsValidEmailDomain" method into my "test" method. Is this possible to achieve?
C#
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);
    }


C#
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.
Posted
Comments
G3Coder 2-Oct-14 12:10pm    
Hi,

If you don't catch the exception in IsValidEmailDomain() it will be passed up the stack to the calling code, i.e. test(). So if you put the catch block there (in test()) your requirements will be met.

Thanks

1 solution

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:

C#
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...
            }
 
        }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900