Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

What are industry standard best practices for implementing custom exceptions in C#?

What are industry standard best practices for implementing custom exceptions in C#?

I have checked Google and there's a great number of recommendations, however I don't know which ones hold more credibility.

If anybody has any links to authoritative articles, that would also be helpful.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The standard for creating custom exceptions is to derive from Exception. You can then introduce your own properties/methods and overloaded constructors (if applicable).

Here is a basic example of a custom ConnectionFailedException which takes in an extra parameter which is specific to the type of exception.

[Serializable]
public class ConnectionFailedException : Exception
{
    public ConnectionFailedException(string message, string connectionString)
        : base(message)
    {
        ConnectionString = connectionString;
    }

    public string ConnectionString { get; private set; }
}

In the application this could be used in scenarios where the application is attempting to connect to a database e.g.

try
{
    ConnectToDb(AConnString);
}
catch (Exception ex)
{
    throw new ConnectionFailedException(ex.Message, AConnString);
}

It's up to you to then handle the ConnectionFailedException at a higher level (if applicable)

Also have a look at Designing Custom Exceptions and Custom Exceptions


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...