On Mon, 22 May 2006 20:19:36 +0200, "Martijn Mulder" <i@m> wrote:
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;
}
}
--
Marcus Andrén