What are custom exceptions in C.


1. What is an exception in C #?

Exceptions are errors that occur during program operation and exception handling is part of the program. The exception classes in C # are mainly derived, directly or indirectly, from the System.Exception class, which means that the System.Exception class is all the base class for predefined system exceptions. The occurrence of errors is not always the cause for the programmer using the wrote the application, and sometimes the application may be incorrect due to incorrect operation by the end user. In either case, predict application and code errors before writing any program.


2. What are the most common anomalies?

        ①    ArrayTypeMismatchException

This exception occurs when the data stored in the array is different from the data type defined by the array

        ② DivideByZeroException

        This exception is thrown when an integer is divided by zero

        ③ IndexOutOfRangeException

        Array out of bounds exception

        ④ NullReferenceException

        The object reference is a zero exception

        ⑤ OverflowException

        Arithmetic overflow

        ⑥ InvalidCastException

        Conversion forced at run time invalid exception


Three, exception handling

        Use the following code structure to catch and handle exceptions

In the finally code block, after the execution of the try-catch structure has been completed, the finally code block is executed regardless of the occurrence of an exception. Even if the code is returned in the try-catch structure, it executes the finally block of code and then returns.

Next, let's look at a simple example of exception collection and handling:

It's worth noting that it is recommended that you use throw to throw an exception. Because throw ex deletes all previous information, you think that the exception you caught was handled, but that the process is just throwing a new exception, so you cannot find the code location where the exception actually occurred.

Four, custom exception

        The custom exception should have the following three characteristics:

① Inherited from System.ApplicationException class and use Exception as the end of the custom exception class name

It contains three constructors: a parameterless constructor, a string parameter constructor, a string parameter and an internal exception as a parameter for the structure of the function

③ ③ Throw a custom exception: Throw a new MyException (); Catch a custom exception: Catch (MyException) {}}

for example:

V. Summary

The advantages of exception handling:

If an error occurs in the program, the program does not crash. However, a prompt can be displayed to improve the user experience

For developers, you can find the bug location in a short amount of time, thereby improving efficiency