Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Exception Handling 1

Status
Not open for further replies.

adamroof

Programmer
Nov 5, 2003
1,107
US
In a recent post response, it was posted in an email catch to use
Code:
catch(SmtpException exception)
{
   Log.Error(exception);
}

What if it is not an SmtpException? Would it bomb the code?

Is this not contained in the catch(Exception ex) statement as well? i understand that it is a general exception, but it does throw the correct error to me if there is one.

Should we double catch?
Code:
catch(SmtpException exception)
{
   Log.Error(exception);
}
catch(Exception generalExc)
{
   Log.Error(generalExc);
}

 
i understand that it is a general exception, but it does throw the correct error to me if there is one.
it throws the correct error because of OOP and polymorphism.
What if it is not an SmtpException? Would it bomb the code?
yes it would fail if the exception was not an SmtpException. there are a variety of guide lines about how to handle exceptions. what i try to follow is this:
1. only catch what I can handle, if all I'm going to do is log it than let if fail higher up the chain.
2. catch the most specific error. if i'm sending an email, and want to handle an exception, then all I care about is smtp exceptions. any other exception is outside the scope of this operation.
3. use try/finally (or using()) as much as possible to clean up resources.
4. if i catch a fatal exception wrap this exception in a custom exception I define to explicitly reveal the intent of the error.
example
Code:
public void GenerateReport()
{
  try
  {
      ReportFormat.MergeWith(GetData()).ExportTo(file);
  }
  catch(IOException ex)
  {
     throw new ReportExportExpection("specific message", ReportFormat, file, ex);
  }
  catch(Exception ex)
  {
     throw new ReportGenerationExpection("specific message", ReportFormat, ex);
  }
}
where ReportExportExpection, ReportGenerationExpection are object I created which inherit from Exception.

recently I have reduced the number of try/catch statements in my projects to 1 or 2. one of them being then HttpApplication.Error event.

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Most excellent.

So me being lazy and wanting to not fully understand what possible errors could be thrown within the call is "okay", but definitely could be handled better.

I do use the multiple catches, but for my file management where i use the different exceptions to handle the events, like the directory doesnt exist or creating directory errors and files.

Your #3 above is leading to another post
 
it's considered expensive to catch/throw exceptions. when possible check for a given scenario before proceeding.
Code:
if(!Directory.Exists(file))
   Directory.Create(file);
string[] files = Directory.GetAllFiles();

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Yes, i do that, this aint one of my best examples, but shows the implementation. The DirectoryInfo would throw one of the IOExceptions.
Code:
public string saveFiles(string tID)
{
    string strMessage = "";
    string strFileName = "";
    string dirPath = root + tID + "/" + sectionReportID.ToString() + "/";
    HttpPostedFile objFile;
    try
    {
        if (!(Directory.Exists(dirPath)))
        { DirectoryInfo di = Directory.CreateDirectory(dirPath); }

        for (int i = 0; i <= Request.Files.Count - 1; i++)
        {
            objFile = Request.Files[i];
            if (objFile.FileName.Length > 0)
            {
                strFileName = objFile.FileName;
                strFileName = strFileName.Substring(strFileName.LastIndexOf("\\") + 1);
                if (File.Exists(dirPath + strFileName))
                    replaceFile = true;
                replaceFile = false;
                objFile.SaveAs(dirPath + strFileName);
                ViewState["filename"] = strFileName;
                strMessage += "Uploaded File: " + strFileName;
                ViewState["path"] = "files/" + tID + "/" + sectionReportID.ToString() + "/" + strFileName;
                uploadSuccess = true;
            }
        }
    }
    catch (IOException dirEx)
    {
        strMessage = "Failed Creating Directory " + dirEx.Message + "<br>";
        uploadSuccess = false;
    }
    catch (Exception err)
    {
        audits.Audit(err.ToString(), "Exception Error", Request.Url.AbsolutePath);
        strMessage = "Failed uploading " + strFileName + ": " + err.Message;
        uploadSuccess = false;
    }
    return strMessage;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top