简体   繁体   中英

How do i catch the CS7036 error

So I am fairly new to C#, and I've been learning by translating my code from python to C#. Now the problem I've stumbled upon, is: how do i catch the CS7036 error. It's called an "AttributeError" in python, and it happens, if you try to instantiate a class, without the required amount of arguments.

public Vector Crossproduct(Vector other)
{
    try
    {
        List<double> output = new List<double>()
        {
            Y* other.Z - other.Y * Z,0 - (X * other.Z- other.X * Z),X* other.Y - other.X * Y
        };
        Vector outputvector = new Vector(output);
        return outputvector;
    }
    catch (Exception)
    {

        throw;
    }
}

I've Googled this and found that there is almost nothing on this error. Here's a link to Microsoft's documentation for C#. Here and here.

My problem is not how to fix the error, but how to catch it, just so I'm clear.

You are misunderstanding something fundamental here. Compiler errors are not runtime exceptions; they are the compiler telling you that the code is not legal at all . There is no facility for catching compiler errors at runtime because the illegal code will never run in the first place; it's illegal!

Now, there are situations in C# where a compiler error gets generated at runtime involving dynamic . That is: C# has a subsystem which allows it to interoperate with dynamic languages (such as Python or JavaScript). When using that feature, decisions which would normally be made at compile time are deferred until runtime, and in that situation, you can in fact be in scenario where you have to catch a compiler error at runtime.

You are not in that situation, and it is rare to be in a dynamic situation that involves a constructor. If you are in that situation in the future, the exception you want to catch is RuntimeBinderException .

See How does having a dynamic variable affect performance? for some thoughts on how dynamic works, if this subject interests you.

C# is a compiled language, so you don't have to 'catch' this sort of error, as the compiler will catch it for you. Your code simply will not compile if you attempt to call a class constructor without the required parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM