SoFunction
Updated on 2025-03-08

Summary of how C# handles exceptions

Regarding exceptions, we have been with us since we started writing code, but we were not yet in the beginning and there was no consciousness in our minds. This is an exception.

Exception: An error occurred during the program running.

Exception object: encapsulates various errors that occur in the program into objects

I remember that during the first interview, the interviewer asked me a turning question like "How do you solve various problems that arise?" a: I was shocked at the time and mentioned this question when I read other people's interview scriptures. I didn't think much about it. First, I looked for some errors, and positioned them to see what abnormalities occurred." q: Then tell me what exceptions are there, the causes of the exceptions, and how to deal with them. a: Null pointer, an exception beyond the index, en en...... It was quite embarrassing at the time. When I asked about the exception, I answered so simply and lacked thinking.

In actual work, catching exceptions and collecting and analyzing exceptions are crucial to solving problems.

Exception class analysis

The SystemException class inherits Exception. The former is the base class of all other exception classes in the System namespace. When catching exceptions, the first thing I check is the Exception object information. The important members of Exception are shown in the following figure

Write a picture description here

  • Properties: Error message that produces the cause of the exception
[__DynamicallyInvokable]
public virtual string Message
{
    [__DynamicallyInvokable]
    get
    {
        if (this._message != null)
        {
            return this._message;
        }
        if (this._className == null)
        {
            this._className = ();
        }
        return ("Exception_WasThrown", new object[] { this._className });
    }
}

The Message property is a read-only property, and GetRuntimeResourceString is a string to get the runtime resource. The returned string is an error message or an empty string that produces the exception.

  • : The set of key/value pairs of other exception information
public virtual IDictionary Data {  
            get {
                if (_data == null) 
                  if(IsImmutableAgileException(this))                            _data = new EmptyReadOnlyDictionaryInternal();
                  else
         _data = new ListDictionaryInternal(); 
                return _data; 
            } 
        }
  • : The name and signature of the method called before the exception occurs
public static string StackTrace
{
    [SecuritySafeCritical]
    get
    {
        new EnvironmentPermission().Demand();
        return GetStackTrace(null, true);
    }
}
  • Properties: Contains the name of the application or object that generated the exception
  • Attribute: Method to raise the current exception
  • Method: Return, it is the "base" class of all exception classes.

Common exception classes

There are many exception types, they are all inherited from SystemException. These exception types are roughly divided into the following types: 1. Related to array sets 2. Related to member access 3. Related to parameters 4. Related to arithmetic 6. Of course, there are some other exceptions.

1. Related to array collection

  • IndexOutOfRangeException class: Exception raised by index out of range
  • ArrayTypeMismatchException class: Exception caused by incorrect data type storage in the array collection
  • RankException class: handles exceptions caused by dimension errors

Related exceptions

IO-related exceptions are inherited from the IOException class, which is used to handle exceptions raised when performing file input and output operations. The 5 directly derived classes of the IOException class are as follows.

  • DirectoryNotFoundException class: Exception raised when the specified directory is not found.
  • FileNotFoundException class: Exception raised when no file is found.
  • EndOfStreamException class: handles exceptions that have reached the end of the stream and have to continue reading the data.
  • FileLoadException class: Exception raised by the file cannot be loaded.
  • PathTooLongException class: Exception caused by file name too long.

3.Exception related to member access

Exceptions related to member access are inherited from the MemberAccessException class, which is inherited from SystemException.

  • FileAccessException: Exception caused by failed access to field member
  • MethodAccessException: Access method member failed to throw an exception
  • MissingMemberException: The member does not have an exception raised

4. Parameter-related exceptions

The exception class ArgumentException related to parameters is inherited from SystemException. Exception occurs when passing parameters to method members.

  • ArgumentOutOfRangeException: Exception raised when a parameter is not within the given range
  • ArgumentNullException: Exception raised when the parameter is null (null is not allowed)

5.Related to arithmetic

The ArithmeticException exception class is used to handle exceptions related to arithmetic. Its related subclass is as follows

  • DivideByZeroException: An exception caused by integer decimal attempt to divide by 0 (the dividend cannot be 0)
  • NotFiniteNumberException: An exception caused by infinity or non-negative values ​​occurs in floating point operation

6. Other exceptions

  • NullReferenceException: When an object is not instantiated and references the exception raised
  • InvalidOperationException: An exception is raised when the current state of the calling object to the method is invalid.
  • InvalidCastException: Handle exceptions raised during type conversion
  • OutOfMemoryException: Handle exceptions caused by insufficient memory
  • *Exception: Handle errors caused by stack overflow

Exception capture

C# provides a structured exception handling solution. All possible exceptions must be properly handled. Try catch itself will not affect the performance of the system. Try catch will not affect the system performance when no exception occurs. When affected, it is an abnormality.

Keyword try catch finally. First execute the statement in try. If an exception is thrown, it will be caught by the catch. Regardless of whether an exception occurs or not, the statement in finally will be executed. In addition, the throw keyword is not commonly used: When the problem occurs, the program throws an exception.

class Program
    {
        static void Main(string[] args)
        {
            DivideNumber div = new DivideNumber();
            (2, 0);
            ();
        }
    }
    class DivideNumber
    {
        int result;
        public DivideNumber()
        {
            result = 0;
        }
        public void DivideMethod(int a,int b)
        {
            try
            {
                result = a / b;
            }
            catch (DivideByZeroException e)
            {
                ("exception, the dividend cannot be 0, :" + );
            }
            finally {
                ($"{a}Divide by{b}The result is"+result);
            }
        }
    }

Exception handling principles and suggestions

In actual development, how to write exceptions or have certain requirements for system stability and fault tolerance.

To catch specific exceptions

When catching exceptions, we often habitually write catch(Exception ex) . This is not a specific exception. It is best to specifically refer to exception classes such as ArgumentException and FormatException. Do not throw "new Exception()"

Nothing is done in catch, exceptions must be thrown to the top layer

This situation may be more common when writing demos by yourself. Do nothing while writing catch (Exception ex) code, don't do this. Remember to throw an exception on the top level

Use finally blocks reasonably

The finally keyword is executed no matter what type of exception is thrown. Most of the time, the code that can be executed under the finally block can also be written in the catch. So under what circumstances is it more appropriate to use the finally keyword, such as cleaning resources, closing streams, replying to status, etc.

The thrown exception needs to be recorded

Of course, not all exceptions that occur in the program must be recorded, and some exceptions are recorded to facilitate the analysis of specific problems. Some logging log libraries log4net ,EIF...

Don't just record the values, you also need to record ()

In the previous example, I printed , just output "try to divide by 0". The error message prompted is not specific, and it is not recommended to do so. The Tostring method contains stacktrace, internal exception information, and Message... Usually these information is more important than just one Message.

Don't use "throw exception" as a result of function execution

"Throw an exception" should be thrown to the top level, but it cannot be used as a result of the method execution, and the result of the method cannot be an exception class.

Each thread must contain a try/catch block

When creating a child thread to execute a task, the main thread will not know the exceptions of the child thread, so each thread needs a try and catch.

Comments from "Code Thinker"

When I was working as a project manager for a C# project, I also thought about how to effectively practice exception handling in the project team.

First, exception handling should be part of the system design regulations that appear in the system design documentation, not just a technical implementation.

As part of the design documentation, exception handling should focus on system fault tolerance and stability (as mentioned by the author). Then, according to this regulation, we will discuss and select various technical details used in exception handling in detail.

For example, when designing a service, exceptions must be handled at the service's calling interface, otherwise any harmful data transmitted from the client may cause the server to hang up.

For example, the handling of exceptions must be clearly stated in the system design, and exceptions cannot be handled in any module.

The above is my personal experience, and I hope that friends who have visited will communicate more.

This is all about this article summarizing the way C# handles exceptions. I hope it will be helpful to everyone's learning and I hope everyone will support me more.