Solved

Good Exception handling C#

Posted on 2011-03-24
4
398 Views
Last Modified: 2012-05-11
hi all,

i've got a question.
I have a method that downloads and saves an image from the web and then shows it in a picture box. Along with that it fills some textboxes and listviews too.
Now I want to know how I best handle exceptions. All this logic is captured in a try catch block, with one exception. However I want to have more control about the exceptions thrown.
Different errors can arise here, do I need to wrap each critical step into a try catch block?
See my code below.
Thx for any help/explanation.

private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
      try
      {
        if ((e.Cancelled == true))
        {
          toolStripStatusLabelInfo.Text = "Action canceled!";
        }

        else if (!(e.Error == null))
        {
          toolStripStatusLabelInfo.Text = ("Error: " + e.Error.Message);
        }

        else
        {
          // Fill textfields
          linkLabelImdbUrl.Text = _singleMovieInfo.ImdbUrl;
          textBoxTitle.Text = _singleMovieInfo.Title;
          textBoxPlayTime.Text = _singleMovieInfo.Runtime + " minutes";
          textBoxRating.Text = _singleMovieInfo.Rating + "/10";
          textBoxReleaseDate.Text = _singleMovieInfo.ReleaseDate;
          textBoxStory.Text = _singleMovieInfo.Storyline;

          // download and save poster image
          string savePosterFileName = Path.Combine(_dataPath, replaceCharsInMovieFile(_singleMovieInfo.Title) + @".jpg");
          Image image = null;
          if (!File.Exists(savePosterFileName))
          {
            image = GuiHelper.DownloadImage(_singleMovieInfo.Poster); // download image -> critical!
            if (image != null)
            {
              image.Save(savePosterFileName); // save image -> critical!
            }
          }
          else
          {
              image = Image.FromFile(savePosterFileName);
          }
          pictureBoxCover.Image = null; // clear the picturebox
          pictureBoxCover.Image = image; // set picturebox image -> critical!
          GuiHelper.SetImage(pictureBoxCover); // resizes the image to fit the picturebox

          // Load castmembers
          listViewCast.Clear(); // add items to listview -> can be critical!
          for (int i = 0; i < _singleMovieInfo.Cast.Count; i++)
          {
            ListViewItem listItem = new ListViewItem(_singleMovieInfo.Cast[i].ToString());
            listViewCast.Items.Add(listItem);
          }

          toolStripStatusLabelInfo.Text = "Done!";

          // Clear the object _singleMovieInfo
          _singleMovieInfo = null;
        }
      }
      catch (Exception ex) // Too general error..
      {
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
    }

Open in new window

0
Comment
Question by:Pit76
4 Comments
 
LVL 5

Expert Comment

by:morgulo
ID: 35210656
try
{
}
catch(InvalidOperationException ex)//first excetion type
{
}
catch(ArgumentException ex)//second exception type
{
}
....
catch(Exception ex)//all other exceptions
{
}
0
 

Author Comment

by:Pit76
ID: 35211124
Thx for your reply. I thought it would be something like that but, how can i know what type of exceptions can occur?
Another question, if the saving of the image fails, I shoudl get a warning but the code should continue. How would I do that?
0
 
LVL 29

Expert Comment

by:anarki_jimbel
ID: 35211249
\
....
catch(Exception ex)//all other exceptions
{
}
finally
{

}

In finally you have code that should run in any case, even if exception occurs.

The first question about types of exception is a bit more tricky.

Partly you may get the answer testing your application. Say, what happens (what type of exception) if download link is not valid? Or connection is broken?
If you are ytrying to save something on a disk - IOException has to be handled. And so on.
0
 
LVL 4

Accepted Solution

by:
Sathish DV earned 500 total points
ID: 35212965
Hi,

It is always better to handle the specific exception type
eg.)
try
{
}
catch(ArgumentNullException ex)
{
}
catch(ObjectNotFound ex)
{
}
finally
{
//code to be run irrespective of exception occured.
}

It is always recommended to use specific exception type. If you use generic Exception type then you wont be knowing which causes the exception. And also while using non-specific Exception type, you wont be having the details in the stack trace which exception is thrown , which inturn makes ur debugging much trivial.

To know which exception type to handle, you need to read the documentation. Visit http://msdn.microsoft.com/en-us/library/ms173160(v=VS.100).aspx

Also visit Microsoft's Patterns and Practices site, and browse through Exception Handling Application Block in  Enterprise Library 5.0, where u can find lot of information on how to identify which exception type to be handled and how to handle. visit http://msdn.microsoft.com/en-us/library/ff664698(v=PandP.50).aspx

0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now