3

In my project I have an object whose constructor can throw. So the code I'm using all across is as follows:

MyObject obj = null;
try
{
    obj = new MyObject();
    obj.DoSomething();
}
finally
{
    if (obj != null)
        obj.Free();
}

As meantioned in Uses of "using" in C#, the code like

using (MyObject obj = new MyObject())
{
    obj.DoSomething();
}

is converted by the .NET CLR to

{
    MyObject obj = new MyObject();
    try
    {
        obj.DoSomething();
    }
    finally
    {
        if (obj != null)
            ((IDisposable)obj).Dispose();
    }
}

The question is: can I somehow make CLR put object's constructor into a try block?

5
  • msdn.microsoft.com/en-us/library/vstudio/… Commented Nov 7, 2013 at 9:02
  • If you need a Try/Catch around your object initialization you need to add it yourself. Commented Nov 7, 2013 at 9:03
  • 1
    "The key point is to".... ? Commented Nov 7, 2013 at 9:12
  • Yeah, sorry about "key point" Commented Nov 7, 2013 at 9:32
  • @TimSchmelter My aim was to rewrite the code with "using" statements. Try/Catch is how it works now Commented Nov 7, 2013 at 9:36

2 Answers 2

5

The question is: can I somehow make CLR put object's constructor into a try block?

No. Or rather, it's pointless to do so, from a resource management perspective. If an exception is thrown by the constructor, then there won't be a reference assigned to obj, so there'll be nothing to call Dispose on.

It's critical that if a constructor throws an exception, it disposes of any resources it allocated, as the caller won't be able to.

Sign up to request clarification or add additional context in comments.

Comments

3

No you can not do that as, this is using and it works in that way. You have to write the code you need by yourself

Worth mentioning that having exception in ctor of the type, is not a good idea at all, so may be , if this is possible move the code that can potentially raise an exception to another place. It's better to have one more method and constrain consumer of your type to call that explicitly in order to achieve something and having control over situation, then having situations like you describe.

In general, use ctor only for construction of the instance of a given type and initialization of internal values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.