p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   C# 2008 aka C# 3.0 (http://p2p.wrox.com/forumdisplay.php?f=354)
-   -   Exception handling (http://p2p.wrox.com/showthread.php?t=75913)

codehelp August 27th, 2009 02:54 AM

Exception handling
 
Hi,
I have a method which returns a data table.
The data access code is in a try catch block.

Code:

public DataTable GetData(string fileName)
        {
            string methodmessage;

            DataTable dt;

            string sqlSelect = "SELECT * FROM " + fileName;

            try
            {
                OleDbConnection cn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= C:\;Extended Properties=""Text;HDR=No;FMT=Delimited""");
                OleDbCommand cmd = new OleDbCommand(sqlSelect, cn);
                OleDbDataAdapter da = new OleDbDataAdapter(cmd);

                dt = new DataTable("SalesRep");
                dt.Locale = CultureInfo.InvariantCulture;
                da.Fill(dt);
            }
            catch (OleDbException oleEx)
            {
                methodmessage = oleEx.Message;
            }

            return dt;
        }

In the calling part of the program I have it like this:

Code:

this.dtperson = new DataTable();
this.dtperson = Form1.GetData(@"C:\TempCsvFiles\person.CSV");

My question is if an exeception occurs in the GetData code, what needs to be done to handle that in the call

Code:

this.dtperson = Form1.GetData(@"C:\TempCsvFiles\person.CSV");
as the GetData method returns a data table.

Thanks and Regards.

samjudson August 27th, 2009 05:40 AM

When you say "what needs to be done" it depends greatly on what you want to happen.

In the case above nothing happens - a blank dataset is assigned to the dtperson property. If this is what you want to happen then you're done.

If you want something else to happen then you have to decide what that is before we can help you write code to do it.

codehelp August 27th, 2009 07:00 AM

I would like to show the exception that is being caught and assigned to methodMessage variable.
That way the use is informed of what has happened.

Thanks and Regards.

samjudson August 27th, 2009 07:07 AM

Well in that case get rid of the try/catch inside the method, and just catch it in the outer code:

Code:

try
{
this.dtperson = Form1.GetData(@"C:\TempCsvFiles\person.CSV");
}
catch(Exception ex)
{
    MessageBox.Show("An exception occurred: " + ex.Message);
}


codehelp August 27th, 2009 07:46 AM

Thank you samjudson.


All times are GMT -4. The time now is 08:28 AM.

Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.