exceptions in 'using statement'

  • Thread starter Thread starter Mohd Ebrahim
  • Start date Start date
M

Mohd Ebrahim

Hello,

my code looks like this by 'using statement'

but how can i check for exception (catch statement) & write to log file in
the following code?

private void NewCustomer()
{
using (frmCustomerEntry obj = new frmCustomerEntry())
{
obj.ShowDialog();
}
}

Regards,
 
Mohd Ebrahim said:
but how can i check for exception (catch statement) & write to log file in
the following code?

private void NewCustomer()
{
using (frmCustomerEntry obj = new frmCustomerEntry())
{
obj.ShowDialog();
}
}

You can check in two ways depending on wether you want to catch errors
only in the ShowDialog line or also in the frmCustomerEntry constructor:

(1)

private void NewCustomer()
{
using (frmCustomerEntry obj = new frmCustomerEntry())
{
try
{
obj.ShowDialog();
}
catch (Exception ex)
{
//Write to log
}
}
}

(2)

private void NewCustomer()
{
try
{
using (frmCustomerEntry obj = new frmCustomerEntry())
{
obj.ShowDialog();
}
}
catch (Exception ex)
{
//Write to log
}
}

Or (3) replace the using block with Try...Catch...Finally:

private void NewCustomer()
{
frmCustomerEntry obj;
try
{
obj = new frmCustomerEntry();
obj.ShowDialog();
}
catch (Exception ex)
{
//Write to log
}
finally
{
((IDisposable)obj).Dispose();
}
}
 
Mohd Ebrahim wrote :
Hello,

my code looks like this by 'using statement'

but how can i check for exception (catch statement) & write to log file in
the following code?

private void NewCustomer()
{
using (frmCustomerEntry obj = new frmCustomerEntry())
{
obj.ShowDialog();
}
}

Regards,

Add an extra try/catch:

private void NewCustomer()
{
using (frmCustomerEntry obj = new frmCustomerEntry())
{
try
{
obj.ShowDialog();
}
catch (Exception ex) // better: some specific exception
{
// log the exception
throw;
}
}
}


Hans Kesting
 
Back
Top