samedi 25 avril 2015

C# VS doesn't handle exception in constructor when using reflection [duplicate]

This question already has an answer here:

Assuming this class:

public class Smurf
    {
        public Smurf()
        {
            throw new Exception("Smurfs do not exist");
        }
    }

When trying to create an instance like this, it works as expected:

    try
    {
        var smurf = new Smurf();
    }
    catch (Exception)
    {

    }

However when using reflection VS incorrectly tells me that my exception is unhandled.

    try
    {       
        var smurf = (Smurf)Activator.CreateInstance(typeof(Smurf));
    }
    catch (Exception)
    {

    }

I've spent hours trying to find the initial problem when I finally came up with this as I was sure I was handling the exception correctly. I believe there are some settings (not quite sure though) in VS which I could use to stop this from happening, but I don't really want to thing about that since the code is deployed for other users and they would have to do the same.

Is there any other way or solution to this?





Aucun commentaire:

Enregistrer un commentaire