Solved

Good Exception handling C#

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

Ready to get started with anonymous questions?

It's easy! Check out this step-by-step guide for asking an anonymous question on Experts Exchange.

Question has a verified solution.

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

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…

627 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