Home  >  Article  >  Backend Development  >  C# basic knowledge compilation: basic knowledge (13) exception

C# basic knowledge compilation: basic knowledge (13) exception

黄舟
黄舟Original
2017-02-11 13:29:531418browse

Often when we write code, we always encounter certain problems during operation that cause the program to crash. This is not because the programmer's level is not good, but because of problems with the business logic, operating system, or other equipment such as computers. For example, some methods in user32.dll are often used in C#. If this file is deleted , your program still cannot run. Of course, as a skilled programmer, you always need to take various situations into consideration when writing a program. The higher the level, the more situations you have to consider, and the more you consider, the less chance your program will crash. The better the robustness.
Generally speaking, there are two situations when the program cannot run:
One is an error. It includes environment errors (such as missing files, incorrect file content, resulting in inconsistency with the program agreement, unsupported system versions, etc.); memory operation errors (such as insufficient memory leading to failure to allocate memory); program logic errors (this is generally Process errors lead to wrong results in the program, etc.);
The second is exceptions. An exception means that the program cannot run due to factors in the current process or unexpected behavior. Generally include:
Illegal operations, the user inputs wrong instructions; abnormal input and output, non-hardware problems when accessing external devices, such as when reading and writing hard disks, the result is that external virtual optical drives, floppy disks, etc. are also used as hard disks, or There is no problem with the program itself, but errors are still reported when reading and writing from the hard disk; memory allocation is abnormal and when memory is insufficient, new objects cannot be created.
Generally speaking, there is a key difference between errors and exceptions. Errors are not allowed to occur. Once they occur, the program must be modified and the operating environment must be changed; exceptions are part of the program, no matter what program is more or less All types of exceptions will be encountered. When exceptions occur, the program must handle exceptions, but exceptions should not affect the continued operation of the program. For errors, correct them when they occur. Let’s take a look at exception handling in C#.
Generally speaking, in order to ensure that the program does not make mistakes, a lot of if...else judgments will be made. However, a wise man will make mistakes after careful consideration. Even a master cannot make the program comprehensive and think of all situations. So this is the way we should use exception handling in C#. C# uses a catch-and-throw model to handle exceptions. When an exception occurs in the program, the exception object is captured at the place where the exception is handled. What is thrown is an object of the Exception class or its subclass, such as:
ArgumentException: This exception is thrown when the parameter is illegal.
ArgumentNullException: This exception is thrown when the parameter is null.
ArgumentOutOfRangeException: This exception is thrown when the parameter exceeds the allowed range.
The format for capturing exceptions is as follows:

            try
            {
                //代码段
            }
            catch (Exception ex)
            {
                //处理异常
            }
            finally
            {
                //最后一定执行的
            }

The try code block contains code that may cause exceptions. You can use the throw keyword to throw exceptions, or you can access any properties or methods that may throw exceptions;
catch code block is used to capture the exception to be caught and contains the code to handle the exception;
finally code block represents the code segment that is executed after the exception handling is completed, that is, the code segment in finally is always executed last, and No matter whether the exception is caught or not.
Look at the following pieces of code:
Inherited from Exception and intuitively understand the Exeption class:

  public class MySelfException : Exception
    {
        /// <summary>
        /// 默认构造器
        /// </summary>
        public MySelfException()

            : base()
        {

        }
        /// <summary>
        /// 提供一个string类型的参数构造器,可设置自定义信息
        /// </summary>
        /// <param name="message"></param>
        public MySelfException(string message)

            : base(message)
        {

        }

        /// <summary>
        /// 用于传入异常信息,另外可以传入该异常有哪个其它异常引发的
        /// </summary>
        /// <param name="message"></param>
        /// <param name="innerException"></param>
        public MySelfException(string message, Exception innerException)

            : base(message, innerException)
        {

        }
        /// <summary>
        /// 覆盖Message属性,返回经过处理的异常信息
        /// </summary>
        public override string Message
        {
            get
            {
                return "有异常:" + base.Message;
            }
        }
    }

Look at the process of catching and throwing:

  public class Exceptions
    {
        public static void PersonInfo(string name, char sex, int age)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            if (sex != &#39;男&#39; && sex != &#39;女&#39;)
            {
                throw new ArgumentException("sex只能为“男”或“女”");
            }

            if (age <= 0 || age >= 150)
            {
                throw new ArgumentOutOfRangeException("age");
            }

            Console.WriteLine(string.Format(@"name={0},sex={1},age={2}", name, sex, age));
        }

        public static void Throwable(bool canThrow, int num)
        {
            if (canThrow)
            {
                throw new MySelfException("测试异常");
            }

            Console.WriteLine(1 / num);

            Console.WriteLine("木有抛出异常");
        }
    }

//Call:

   class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Exceptions.PersonInfo(null, &#39;男&#39;, 22); 

                // Exceptions.PersonInfo("Purple", &#39;呵呵&#39;, 22);

                Exceptions.PersonInfo("Purple", &#39;男&#39;, 1000);

                //Exceptions.PersonInfo("Purple", &#39;男&#39;, 22);

                Console.WriteLine("代码执行无错误");
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine(e.Message);

                Console.WriteLine(e.StackTrace);
            }
            catch (ArgumentOutOfRangeException e)
            {
                Console.WriteLine(e.Message);

                Console.WriteLine(e.StackTrace);
            }
            catch (ArgumentException e)
            {
                Console.WriteLine(e.Message);

                Console.WriteLine(e.StackTrace);
            }

            Console.ReadLine();
        }
    }

You can see that in the try code block, once the program reaches the throw keyword, it immediately stops running the subsequent code, and then jumps to the catch code block corresponding to the throw exception object type for execution. Therefore, the catch-and-throw model is a more intuitive and reasonable way to handle exceptions.

The above is the compilation of basic knowledge of C#: basic knowledge (13) unusual content. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn