Solved

Good Exception handling C#

Posted on 2011-03-24
4
421 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 30

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

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
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.
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

751 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