Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 513117
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T07:23:22+00:00 2026-05-13T07:23:22+00:00

I’m relatively new to C# and .NET and I’m trying to learn how to

  • 0

I’m relatively new to C# and .NET and I’m trying to learn how to better handle exceptions in my code.

Take the following function I’ve written for example:

  public void SendEmail(string SenderEmail, string SenderDisplayName, IEnumerable<string> RecipientEmails, string Subject, string Message)
    {
        MailMessage message = new MailMessage();

        message.From = new MailAddress(SenderEmail, SenderDisplayName);
        foreach (var recipient in RecipientEmails)
        {
            message.To.Add(recipient);
        }
        message.Subject = Subject;
        message.Body = Message;

        SmtpClient smtpClient = new SmtpClient("192.168.168.182");
        smtpClient.Send(message);
    }
}

If you attempt to add an email address that is malformed in Message.From or Message.To, it will throw an exception. Right now my app is just crashing and burning when this happens.

Can someone show me the appropriate way to handle that exception in this method?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T07:23:22+00:00Added an answer on May 13, 2026 at 7:23 am

    This is the appropriate way to handle exceptions!

    In general, an exception should not be handled unless the problem can be corrected, and it should only be handled in a place where the correction can be applied.

    For example, the caller of your code might want to prompt the user to correct the bad email address. But your code can’t know the right way to prompt. Are you being called from WinForms or Web Forms? What should the dialog box look like? Should there even be a dialog box? These are things that can only be known by the caller of your method, and not by your method itself.


    In the caller:

    try
    {
        SendEmail(SenderEmail, SenderDisplayName, RecipientEmails, Subject, Message);
    }
    catch (MyMailAddressException ex)
    {
        MessageBox.Show(ex.Message);
    }
    

    Note that any exceptions other than MyMailAddressException will propagate to code that knows how to handle them.


    Appropriate level of “handling” in your method:

    public enum MailAddressType
    {
        Sender,
        Recipient
    }
    
    public class MyMailAddressException : Exception
    {
        public MailAddressType AddressType { get; set; }
        public string EmailAddress { get; set; }
    
        public MyMailAddressException(
            string message,
            MailAddressType addressType,
            string emailAddress,
            Exception innerException) : base(message, innerException)
        {
            AddressType = addressType;
            EmailAddress = emailAddress;
        }
    }
    
    public void SendEmail(
        string senderEmail,
        string senderDisplayName,
        IEnumerable<string> recipientEmails,
        string subject,
        string message)
    {
        using (
            var mailMessage = new MailMessage
                              {
                                  Subject = subject, 
                                  Body = message
                              })
        {
            try
            {
                mailMessage.From = new MailAddress(
                    senderEmail, senderDisplayName);
            }
            catch (FormatException ex)
            {
                throw new MyMailAddressException(
                    "Invalid from address", MailAddressType.Sender,
                    senderEmail, ex);
            }
    
            foreach (var recipient in recipientEmails)
            {
                try
                {
                    mailMessage.To.Add(recipient);
                }
                catch (FormatException ex)
                {
                    throw new MyMailAddressException(
                        "Invalid to address", MailAddressType.Recipient,
                        recipient, ex);
                }
            }
    
            var smtpClient = new SmtpClient("192.168.168.182");
            smtpClient.Send(mailMessage);
        }
    }
    

    The caller can then catch MyMailAddressException and have all the information necessary to tell the user what to fix. Other exceptions should propagate.


    My previous edits have addressed your question about the method. I have been assuming that your application has appropriate top-level exception handling. Gabriel points out to me that if you had appropriate top-level exception handling, then your application would not be crashing!

    However, crashing is not necessarily a bad thing. If something happens that your code cannot handle, then crashing is the right thing to do. The alternative is to try to continue running, hoping that this unhandled exception hasn’t damaged your program in such a way that it begins to produce incorrect results.

    The specifics of exactly where to put “top-level handlers” depends on your program. It’s different between WinForms and ASP.NET applications, for instance. However, the concept will be the same: safely log all the available information, then allow the exception to propagate, crashing the application.

    Of course, you should be using finally blocks to clean up your application, even in the presence of exceptions.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I have this code to decode numeric html entities to the UTF8 equivalent character.
I want use html5's new tag to play a wav file (currently only supported
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.