try...catch in constructor

  • Thread starter Thread starter Martijn Mulder
  • Start date Start date
M

Martijn Mulder

Is it good style to use a try...catch clause in the constructor or is it
something that is frowned upon?
 
If you can recover from an error in the constructor, it's fine. Otherwise,
no.

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

The man who questions opinions is wise.
The man who quarrels with facts is a fool.
 
The same rules about try...catch that apply to other methods apply to
constructors as well: catch only what you can deal with intelligently.
Other than that, there's no difference that I know of between event
handling / raising in constructors versus other methods.
 
Is it good style to use a try...catch clause in the constructor or is it
something that is frowned upon?

Try-Catch in constructors work exactly as try-catch in methods. Only
catch exceptions if you actually handle it, otherwise let the
constructor throw an exception.

The only exception that I can think of, happens when dealing with
IDisposable objects. Consider the following class

class MyDisposableClass : IDisposable
{
AnotherIDisposableClass memberDisposable;

public MyDisposableClass(string s)
{
memberDisposable = AnotherIDisposableClass();

if(s == null)
throw new ArgumentException(); //Creates a resource leak
}

public void Dispose() //Vert
{
if(memberDisposable != null)
memberDisposable.Dispose();
}
}

In the above code the memberDispoable variable will be created, but it
won't be disposed of. This is an easy to miss resource leak, since it
falls outside of the usual IDisposable/using/try-finally pattern.

This can be fixed in three ways that I can think of.

* Making sure the constructor doesn't cause any exceptions by catching
them all. Catching all exceptions is however bad style, so this is the
worst solution.

* Moving the creation of the IDisposable objects out of the
constructor (or to the end of the constructor if there only is one).

* Using try-catch and call dispose manually in the constructor, like
the following example:

public MyDisposableClass(string s)
{
try
{
memberDisposable = AnotherIDisposableClass();

if(s == null)
throw new ArgumentException(); // This can create a problem
}
catch
{
this.Dispose();
throw;
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top