Solved

Good Exception handling C#

Posted on 2011-03-24
4
406 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

ScreenConnect 6.0 Free Trial

Check out the updates in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI that improves session organization and overall user experience. See the enhancements for yourself!

Question has a verified solution.

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

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

832 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