C# study notes exception handling

System.Exception类

There are many exception classes defined in C#, and all exception classes in C# are System.Exceptionsubclasses. It derives two sub-categories: SystemExceptionand ApplicationException. The former are various exceptions defined by the system, and the latter are provided for application use.
ExceptionThere are two commonly used construction methods:

public Exception();
public Exception(string s);

The second construction method can accept the information passed in by the string parameter, which is usually a description of the error corresponding to the exception. ExceptionClasses have two important attributes: Messageattributes and StackTraceattributes.
Message property: readable text describing the error. In the process of creating an exception object, a text string can be passed to the constructor to describe the detailed information of the specific exception.
StackTrace property The state of the call stack when an exception occurs. Including the stack trace where the error occurred, all the methods called, and the line number of these calls in the source file.

System-defined exception

The following table:
Insert picture description here
Insert picture description here

Catch and handle exceptions

The exception handling mechanism in C# can be summarized into the following steps:

  • ① If an exception occurs during the execution of the C# program, an exception object will be automatically generated, and the exception object will be submitted to the C# runtime system. This process is called throwing an exception. Throwing an exception can also be forced by a program to use a throwstatement.
  • ② When the C# runtime system receives the exception object, it will look for the code that can handle the exception and hand the current exception object to it for processing. This process is called catching the exception.
  • ③ If the C# runtime system cannot find a way to catch the exception, the runtime system will terminate and the corresponding C# program will also exit.

1. Throw an exception

If a C# program causes an identifiable error at runtime, an object of the exception class corresponding to the error will be generated. This process is called exception throwing.
(1) Exceptions automatically thrown by
the system All system-defined operating exceptions can be automatically thrown by the system.
(2) Exceptions thrown by statements
User-defined exceptions cannot be automatically thrown by the system. Instead, throwstatements must be used to define what kind of error corresponds to this type of exception, and a new type of exception is thrown. Object. The format is:

	throw 异常对象;

2. Catch exception catch

When an exception is thrown, there should be a special statement to receive the thrown exception object. This process is called catching the exception. When an abnormal object is caught or received, the user program will jump to the flow. The system terminates the current flow and jumps to a special exception handling block, or jumps out of the current program and terminates.

Use the catchstatement in the C# program , its format is as follows:

	try {
    
    
		语句组
	} catch(异常类名 异常形式参数名) {
    
    
		异常处理语句
	} catch(异常类名 异常形式参数名) {
    
    
		异常处理语句
	} finally {
    
    
		异常处理语句
	}

There is at least one catchstatement or finallystatement.
Finally statement: The finally statement provides a unified exit for exception handling . The statement in the finally block will be executed regardless of whether an abnormal event occurs in the trycode block and the catchblock, and regardless of any statement (that is, use returnor throwthrow an exception).

User-defined exception class

When creating a user-defined exception, you generally need to complete the following tasks:

  • ① Declare a new exception class, making it the ApplicationExceptionparent class or some other existing system exception class or user exception class.
  • ② Define attributes and methods for the new abnormal class, or overload the attributes and methods of the parent class, so that these attributes and methods can reflect the error information corresponding to the class.

E.g:

public class MyAppException : ApplicationException
{
    
    
	public MyAppException(string message) : base(message) {
    
     }
}

Rethrow exceptions and abnormal links

In the system, exceptions can be captured and processed. Sometimes, not only must the exception be processed, but the exception must be further passed to the caller so that the caller can also feel the exception. At this time, you can take the following three ways in the catch statement block or finally statement block:

  • ① Use the throwstatement without expression to throw the currently caught exception again. The format is as follows:
	throw;
  • ② Regenerate an exception and throw it, such as:
	throw new Exception("some message");
  • ③ Regenerate and throw a new exception, which contains the current exception information, such as
	throw new Exception("some message", e);

Among them, the last method is better, because it retains the current abnormal information and returns a more meaningful information to the caller. This approach is called "unusual linking." If the related exceptions are all adopted in this way, the caller at the upper layer can gradually and deeply find the related exception information.
In this way, in addition to Exceptionclass Message, StackTraceattributes and ToString()methods , attributes are also commonly used InnerException.
InnerExceptionIs a read-only attribute that contains the "internal exception" of this exception. If it is not null, it points out that the current exception was thrown as a link to another exception.
In order to InnerExceptionspecify attributes, the following construction methods must be used:

	public Exception(string Message, Exception InnerException);

The second parameter specifies this "internal exception". If it is a user-defined exception, it is generally necessary to provide a construction method, and the internal exception can be specified in the parameter.

The example uses internal exceptions for abnormal linking:

using System;

public class DataHouse
{
    
    
	public static void FindData(long ID) {
    
    
		if (ID > 0 && ID < 1000)
			Console.WriteLine(ID);
		else
			throw new DataHouseException("已收到文件尾");
	}
}

public class BankATM
{
    
    
	public static void GetBalanceInfo(long ID) {
    
    
		try {
    
    
			DataHouse.FindData(ID);
		} catch (DataHouseException e) {
    
    

			throw new MyAppException("账号不存在", e);
		}
	}
}

public class DataHouseException : ApplicationException
{
    
    
	public DataHouseException(string message) : base(message) {
    
     }
}
public class MyAppException : ApplicationException
{
    
    
	public MyAppException(string message) : base(message) {
    
     }
	public MyAppException(string message, Exception inner) : base(message, inner) {
    
     }
}

class Program
{
    
    
	static void Main(string[] args) {
    
    
		Console.WriteLine("Hello World!");

		try {
    
    
			BankATM.GetBalanceInfo(12345L);
		} catch (Exception e) {
    
    
			Console.WriteLine("出现了异常: {0}", e.Message);
			Console.WriteLine("内部原因: {0}", e.InnerException.Message);
		}
	}
}

Guess you like

Origin blog.csdn.net/qq_45349225/article/details/114109201