How to create and use custom exceptions in C#

C# is a strongly typed language that can catch and handle various exceptions, thus helping us find errors in programs. In the process of program development, if you need to find and handle specific error conditions, you need to create custom exceptions. Here's how to create and use custom exceptions in C#.

1. What is an exception?

An exception is an error or abnormal situation that occurs during program execution, such as division by 0 in division, file does not exist, insufficient memory, etc. When an exception occurs, the program will stop executing the current operation and throw an exception object. The exception object contains information about the exceptional condition, such as exception type, error message, stack trace, etc.

C# exception handling is built around four keywords: try, catch, finally, and throw.

1) try- A try block identifies a block of code for which a particular exception is activated. It is followed by one or more capturing blocks.

2) catch- The program uses exception handlers to catch exceptions at the point in the program where the problem is to be handled. The catch keyword catches the exception that occurs.

3) finally - The finally block is used to execute a given set of statements, whether or not an exception is thrown. For example, if you open a file, it must be closed whether or not an exception is thrown.

4) throw - When something goes wrong, the program throws an exception. This is done using the throw keyword.

2. Custom exceptions in C#

Next, let's take a look at how to create a C# exception class. In C#, creating a custom exception is very simple. Just create a class and derive it from the System.Exception class or its subclasses. For example, the following code creates a custom exception class named CustomException:

//创建一个没有错误消息的异常对象
public class CustomException : Exception
{
    public CustomException() { }
    //创建一个包含错误消息的异常对象。
    public CustomException(string message)
        : base(message){throw new Exception(message);}
    //创建一个包含错误消息和内部异常对象的异常对象。
    public CustomException(string message, Exception innerException)
        : base(message, innerException) { }
}

 

Such a custom exception is created.

Use a custom exception class

Using custom exceptions is the same as using built-in exception classes. Just throw the exception object in the program and use the try-catch block to catch the exception. code show as below:

try
{
    //如果是k引发d二异常会报错系统异常
    //int i=0; int j=1;
    //int k=i/j;
    // 某些操作 下面会报自定义异常
    throw new CustomException("发生了自定义异常");
}
catch (CustomException ex)
{
    Console.WriteLine("自定义异常:"+ex.Message);
}
catch (Exception ex)
{
    Console.WriteLine("系统异常:"+ex.Message);
}

 If the above code is divided by 0, a system exception will be reported, and a custom exception will be reported when it is triggered.

3. Custom exception usage scenarios

The above implements the custom exception class, so in which scenarios are custom exception classes usually used?

1) Detect business rules

When we need to check business rules, we can create custom exception classes. For example, we can throw a custom exception called DuplicateAccountException when a user tries to create an account that already exists.

2) Easy to debug

By using custom exception classes, we can better debug our code. When we throw a custom exception, we can pass more useful information to the caller, such as error message, error code and stack trace, etc. This information helps the caller to quickly locate the problem and fix it.

Summarize

Custom exceptions are a great way to handle specific error conditions. By creating custom exception classes, we can better control the behavior of the program and provide useful error messages.

 

Guess you like

Origin blog.csdn.net/lwf3115841/article/details/130643671