Basic knowledge of C #: Basics (13) Exceptions

Source: Internet
Author: User
Often when we write code, we always run into some problems and cause the program to crash. This is not the level of programmers, but by the business logic, operating system, or computer and other equipment problems, such as in C # often used in the user32.dll of some methods, if the file is deleted, your program will not run. Of course, as a level of programmers will always write the program is the need to take into account all kinds of situations, the higher the level of consideration is more, and the more you think about your program crashes the less opportunities, the better the robustness.
In general, there are two scenarios in which a program does not run:
One is wrong. It includes environmental errors (such as missing files, file content errors, resulting in inconsistent with the program contract, system version not supported, etc.), memory operation errors (such as insufficient memory to cause allocation of memory failure), Program logic error (this is usually a process error caused the program to obtain the wrong result, etc.);
The second is the exception. An exception is a program that cannot be run because of current process factors or unexpected behavior. Generally includes:
Illegal operation, the user entered an error command, input and output anomalies, access to external equipment, non-hardware problems, such as reading and writing hard disk, the result will be external virtual CD-ROM, floppy disk, etc. also as hard disk use, or the program itself is not a problem, but read and write hard disk or report errors, etc., memory allocation is abnormal, Causes the new object to be created.
In general, there is a key difference between the error and the exception, the error is not allowed to occur, once it is necessary to modify the program, change the operating environment, and the exception is part of the program, no matter what program will encounter all kinds of exceptions, the exception occurs program will handle the exception, but the exception should not affect the program to continue running. The error is changed when it occurs. Below is a look at the handling of exceptions in C #.
In general, in order to ensure that the program does not go wrong, will do a lot of judgment if...else, but the wise thousand worry must have a loss, even if Daniel always can not let the program exhaustive, all the situation can think of. So this is the way we should handle exceptions in C #. In C #, the catch-and-throw model is used to handle the exception, and when the program has an exception, the exception object is caught in the process of the exception. Throws an object of the exception class or its subclasses, such as:
ArgumentException: This exception is thrown when the argument is not valid.
ArgumentNullException: This exception is thrown when the parameter is null.
ArgumentOutOfRangeException: This exception is thrown when the parameter exceeds the permitted range.
The catch exception format is as follows:

            Try            {                //code snippet            }            catch (Exception ex)            {                //Handle exception            }            finally            {                ///Last must execute            }

The code in the try code block is a possible exception, you can use the Throw keyword to throw an exception, or you can access any property or method that might throw an exception;
The catch code block captures the exception to be caught and contains the code that handles the exception;
The finally code block represents the code snippet that executes after the exception processing ends, that is, the code snippet in finally is always last executed, regardless of whether an exception was caught.
Take a look at the following pieces of code:
Inherit from exception intuitively understand the following Exeption class:

  public class Myselfexception:exception {//<summary>///default builder///</summary> Public myselfexception (): Base () {}///<summary>///provide a string-type parameter construct Customizable information//</summary>//<param name= "message" ></param> public myselfexceptio N (String message): base (Message) {}////<summary>///For passing in exception information, which can also be passed into the exception Other exceptions caused by///</summary>//<param name= "message" ></param>//<param name= "inner Exception "></param> public myselfexception (String message, Exception innerexception): Base (Mes Sage, innerexception) {}///<summary>///Overwrite message property, return processed exception information///</summ Ary> public override string Message {get {return ' has an exception: "+ base.            Message;      }  }    } 

Let's look at the process of grasping 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! = ' man ' && sex! = ' female ')            {                throw new ArgumentException ("Sex can only be" male "or" female ");            }            if (age <= 0 | |, age >=)            {                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 (" Test exception ");            }            Console.WriteLine (1/num);            Console.WriteLine ("Wood has thrown exception");        }    }

Call:

 class program {static void Main (string[] args) {try {                 Exceptions.personinfo (null, ' Male ', 22);                Exceptions.personinfo ("Purple", ' hehe ', 22);                Exceptions.personinfo ("Purple", ' Male ', 1000);                Exceptions.personinfo ("Purple", ' Male ', 22);            Console.WriteLine ("Code Execution error free");                } 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 (); }    }

As you can see, in the try code block, once the program runs to the Throw keyword, the code immediately stops running and jumps to the catch code block corresponding to the throw throw exception object type. Therefore, the catch-and-throw model is a more intuitive and reasonable exception handling method.

The above is the basic knowledge of C #: Basic knowledge (13) exception content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.