kosnkov
kosnkov

Reputation: 5911

How can I get exception code in C#?

Is there anything like exception code? that i can know that on different languages operation system i can recognize the same exception?

I need to recognize 'Acces to the COMn Port is denied' and then do some action, is that possible? has this exception any specified type?

Upvotes: 0

Views: 634

Answers (2)

Samuel Slade
Samuel Slade

Reputation: 8613

From the sounds of it you will be getting a System.UnauthorizedAccessException (this assumption has been made from Googling the error message and finding this forum). To handle this, you would need to use catch clauses in a try-catch statement that are specific to this exception type. So, in C# you would do something like:

try
{
    // ... Run some code that might cause the error in question ...
}
catch (System.UnauthorizedAccessException ex)
{
    // ... Run some code that handles the error in question ...
}

Upvotes: 2

Jon
Jon

Reputation: 437326

There is no concept of a global exception code in .NET -- and there really could never be, since it implies that every author of every exception class on the planet would have to collaborate in order to choose codes.

You also cannot assume that a particular message signals an exception of a particular type, since the message can (in the general case) be freely chosen at the throw site.

You could do a type switch on exception.GetType() to find what the runtime type of an exception is, but that is not guaranteed to be a solution (it depends on what was actually thrown, which could be a vanilla System.Exception for all we know).

What exactly are you trying to achieve?

Upvotes: 0

Related Questions