Link to home
Start Free TrialLog in
Avatar of Pit76
Pit76Flag for Belgium

asked on

Good Exception handling C#

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

Avatar of morgulo
morgulo
Flag of Poland image

try
{
}
catch(InvalidOperationException ex)//first excetion type
{
}
catch(ArgumentException ex)//second exception type
{
}
....
catch(Exception ex)//all other exceptions
{
}
Avatar of Pit76

ASKER

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?
Avatar of Dmitry G
\
....
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.
ASKER CERTIFIED SOLUTION
Avatar of Sathish DV
Sathish DV
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial