C # basic knowledge sorting: Basic knowledge (13) Exceptions

Source: Internet
Author: User

When we write code, we always encounter some problems in the operation, which leads to program crash. This is not caused by problems with business logic, operating systems, computers, and other devices. For example, some methods in user32.dll are often used in C, if this file is deleted, your program will still be unable to run. Of course, as a level programmer, all the situations need to be taken into account when writing a program. The higher the level, the more situations you will consider, the more you think about it, the less chance your program will crash, and the better the robustness.
Generally, a program cannot run in two situations:
1. errors. It includes environment errors (such as missing files, incorrect file content, non-conforming to the program conventions, and unsupported system versions ); memory Operation error (for example, memory allocation failure due to insufficient memory); program logic error (this is generally due to a process error that leads to incorrect results );
Second, exceptions. An exception occurs when the program fails to run due to factors in the current process or unexpected behavior. It generally includes:
Illegal operation. The user entered an incorrect command. The input and output are abnormal and non-hardware problems occur when accessing external devices. For example, when reading and writing a hard disk, the external virtual optical drive and floppy disk are also used as hard disks, or the program itself does not have a problem, but the read/write hard disk still reports an error, etc. Memory Allocation is abnormal, when the memory is insufficient, the new object cannot be created.
In general, there is a key difference between errors and exceptions. errors are not allowed. Once an error occurs, you must modify the program and change the running environment. Exceptions are part of the program, no matter what program encounters more or less all kinds of exceptions, it is necessary to handle exceptions when exceptions occur, but exceptions should not affect the program to continue running. If an error occurs, modify it. The following describes how to handle exceptions in C.
In general, in order to ensure that the program does not go wrong, there will be a lot of judgments if... else, But the wisdom may have a loss, even if the Daniel cannot make the program comprehensive, all the situations can be thought. So this is the way we should use C # To handle exceptions. C # uses the capture and throwing model to handle exceptions. When an exception occurs in the program, the exception object is caught in the exception handling area. An exception class or its subclass object is thrown, for example:
Argumentexception: this exception is thrown when the parameter is invalid.
Argumentnullexception: this exception is thrown when the parameter is null.
Argumentoutofrangeexception: this exception is thrown when the parameter exceeds the permitted range.
The exception capture format is as follows:

Try {// code segment} catch (exception ex) {// handle exceptions} finally {// finally executed}

The try code block may contain exceptions. You can use the throw keyword to throw an exception or access any attribute or method that may throw an exception;
The catch code block is used to capture the exception to be captured and contains the code to handle the exception;
The finally code block indicates the code segment that is executed after the Exception Processing is completed. That is, the code segment in finally is always executed, regardless of whether an exception is caught.
Take a look at the following code:
An intuitive understanding of the exeption class inherited from exception:

Public class myselfexception: exception {// <summary> /// default constructor /// </Summary> Public myselfexception (): Base () {}/// <summary> /// provides a string-type parameter constructor, you can set custom information /// </Summary> /// <Param name = "message"> </param> Public myselfexception (string message): Base (Message) {}/// <summary> /// used to input exception information, in addition, you can specify the other exceptions that cause this exception. /// </Summary> /// <Param name = "message"> </param> /// <Param name = "innerexception"> </param> Public myselfexception (string message, exception innerexception): Base (message, innerexception) {}/// <summary> // overwrite the message attribute, returns the handled exception information /// </Summary> Public override string message {get {return "exception:" + base. message ;}}}

Let's take a look at the capture and throwing process:

Public class exceptions {public static void personinfo (string name, char sex, int age) {If (string. isnullorempty (name) {Throw new argumentnullexception ("name");} If (sex! = 'Male' & sex! = 'Femal') {Throw new argumentexception ("sex can only be" male "or" female ");} 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 ("test exception");} console. writeline (1/num); console. writeline ("an exception thrown by wood ");}}

// Call:

Class program {static void main (string [] ARGs) {try {// exceptions. personinfo (null, 'male', 22); // exceptions. personinfo ("Purple", 'ha ', 22); exceptions. personinfo ("Purple", 'male', 1000); // exceptions. personinfo ("Purple", 'male', 22); console. writeline ("no error in code execution");} 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 the throw keyword, it immediately stops running the code and jumps to the catch code block corresponding to the throw throwing an exception object. Therefore, the capture and throwing model is a more intuitive and reasonable exception handling method.

Code download: http://download.csdn.net/detail/yysyangyangyangshan/4540000

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.