What you should know about. NET error and exception handling mechanism

  • 2021-11-13 01:12:06
  • OfStack

Directory exception class
Use try... catch... finally to catch exceptions
Filter exceptions and create user-defined exceptions

Preface

Errors are not always caused by the person who wrote the program, and sometimes the application will fail because of the action caused by the end user of the application or the environment in which the code is running. In any case, we should predict the errors in the application and code accordingly.

. Net improves the way errors are handled. The C # error handling mechanism provides custom handling for each error and separates the code that identifies the error from the code that handles it.

Exception class

In C #, when a special exception error condition occurs, a Throw 1 exception object is created that contains information to help track the problem. . Net provides many predefined exception classes. Let's take a look at one common exception class (there are too many exception classes, so here are some common exception classes).

For the. Net class, the 1-type exception class System. Exception is derived from System. Object, and generally does not throw System. Exception generic objects in code because they cannot determine the nature of the error condition.

There are two important classes in this hierarchy, which are derived from the System. Exception classes:

SystemException--This class is used for exceptions that are typically thrown by the. NET Allow Library, or by almost all applications. For example, if the. NET runtime detects that the stack is full, it throws an StackOverflowException exception. On the other hand, if you detect that the parameters are wrong when calling the method, you can choose to throw ArgumentException exception or its subclass in your own code. Subclasses of SystemException exceptions include exceptions that represent fatal and non-fatal errors. ApplicationException-In the original design of. NET Framework, this class was intended to be the base class for custom application exception classes. However, some of the exception classes thrown by CLR are also derived from this class. The exception thrown by the application is derived from SystemException. So there is no benefit in deriving a custom exception type from ApplicationException; instead, you can derive a custom exception class directly from the Exception base class.

Other exception classes that may be used include:

StackOverflowException--This exception is thrown if the memory area allocated to the stack is full. If a method calls itself recursively continuously, a stack overflow may occur. This is generally a fatal error because it prevents the application from performing tasks other than interrupts. In this case, it is not even possible to execute to the finally block. Usually, users can't handle errors like this by themselves, but should quit the application. EndOfStreamException--This exception is usually thrown because it is read to the end of a file, and the flow represents the flow of data between data sources. OverflowException--This exception is thrown if you want to cast int type data containing-40 to uint data in an checked context MemberAccessException--This class handles exceptions that are thrown when access to a member of a class fails. The reason for the failure may be that there are not enough access rights, or the member to be accessed does not exist at all (commonly used when calling between classes) IndexOutOfException--This class handles exceptions that are thrown when the subscript exceeds the length of an array

Use try... catch... finally to catch exceptions

The code contained in the try block constitutes the normal operation part of the program, but this part of the program may encounter some serious errors. The catch block contains code that handles errors that are problems when executing the code in the try block. This fast can be used to record errors. finally contains code that cleans up resources or performs other operations typically performed at the end of an try block or an catch block. The finally block is executed regardless of whether an exception is thrown or not. The return statement is prevented in the finally block, and the compiler flags 1 error. In addition, this block can be omitted if there are no other operations that need to be closed or processed.

Exception handling has performance implications, and in common cases, exceptions should not be used to handle errors. You should try your best to write code that avoids errors.

In exception trapping, we can implement multiple catch blocks to make corresponding error handling for different errors. Let's look at an example:


class Program
 {
 static void Main(string[] args)
 {
  while (true)
  {
  try
  {
   string userInput;
   Console.WriteLine(" Please enter 0-5 Arbitrary between 1 Numbers: ");
   userInput = Console.ReadLine();
   if (string.IsNullOrWhiteSpace(userInput))
   {
   break;
   }


   if (int.TryParse(userInput, out int index))
   {
   if (index < 0 || index > 5)
   {

    throw new IndexOutOfRangeException($" The number you entered is {index}");

   }
   Console.WriteLine($" The number you entered is {index}");
   }
   else
   {
   throw new Exception(" Please enter a number ");
   }
  }
  catch (IndexOutOfRangeException ex)
  {
   Console.WriteLine($" The number you entered is not in this range .{ex.Message}");
  }
  catch (Exception ex)
  {

   Console.WriteLine(ex.Message);
  }
  finally
  {
   Console.WriteLine(" Thank you for your cooperation ");
  }

  
  }
 }
 }

In this case, two catch blocks are defined. If the input exceeds the specified number returned, an out-of-range error will be thrown and the corresponding catch block will be entered. The input non-digits also enter another catch block for processing.

Let's take a look at 1 for the System. Exception attribute. Familiarity can better observe and understand the thrown exception errors.

属性

说明

Data

这个属性可以给异常添加键/值语句,以提供关于异常的额外信息

HelpLink

连接到1个帮助文件上,以提供关于该异常的更多信息

InnerException

如果此异常是在catch块中抛出的,它就会包含把代码发送到catch块的异常对象

Message

描述错误情况的文本

Source

导致异常的应用程序名或对象名

StackTrace

栈上方法调用的详细信息,它有助于跟踪抛出异常的方法

Hresult

分配给异常的1个数值

TargetSite

.NET反射对象,描述了抛出异常的方法

Filter exceptions and create user-defined exceptions

Exception filters have been supported since C # 6. The Catch block is executed only when the filter does but true. When catching different exception types, there can be code blocks that behave differently. In some cases, the catch block performs different operations based on the contents of the exception. Let's take a look at how to use exception filters:


 public class MyIndexOutOfException :SystemException
 {
  public MyIndexOutOfException(string message) : base(message)
  {

  }

  public int ErrorCode { get; set; }
 }

 class Program
 {
  static void Main(string[] args)
  {
   try
   {
    int steInput = 12;

    if (steInput > 10)
    {
     throw new MyIndexOutOfException(" The data is out of range ") { ErrorCode = 1 };
    }

   }

   catch (MyIndexOutOfException ex) when (ex.ErrorCode!=1)

   {
    Console.WriteLine(" A custom error occurred ");
   }

   catch (MyIndexOutOfException ex) when (ex.ErrorCode == 1)
   {
    Console.WriteLine(ex.Message);
   }

   catch (Exception ex)
   {

    throw;
   }
  }
 }

In the above example, one exception handling was customized, and colleagues added ErrorCode, which was used as a filtering condition, and the keyword When + was used for filtering.

Summarize

This article introduced the exception handling error situation and the mechanism, we can output not only the code is very sad 1 error code, also can output our own definition of the special error situation. No matter how good the programming technique is, the program must be able to handle any errors that may occur. Taking corresponding countermeasures for different errors is one of the steps of correct coding.


Related articles: