Exception Handling Exception

Source: Internet
Author: User
Tags finally block

First, the Exception class

1. All exceptions in C # are represented by example objects of an exception type that inherit from the System.Exception type, or use the instance object of the System.Exception type directly;

2. In C #, the code in the finally block guarantees that the statement will be executed regardless of whether the code ends normally or enters an exception-handling block of code.

The System.Exception class has some properties to note that these properties are shared by all exception classes derived from this class, which are:

Message: A read-only string that provides descriptive information for the current exception;

InnerException: A read-only property of a exception type that, if its value is not NULL, can get the exception instance that caused the current exception by its value, or, conversely, if its value is null, it means that the current exception was not raised by another exception.

StackTrace: A read-only string that describes the contents of the call stack when an exception occurs, first displaying the most recent method call.

Second, throw an exception

When the program has an error, you can create an exception object that describes the error, and then throw the exception object with the Throw keyword, and the thrown exception object will be caught by the higher-level code of the current code, or not directly thrown, or simply not captured. Then the exception will be passed up until someone captures and processes it.

    Class program    {        static void Main (string[] args)        {            dosomething (null);            Console.readkey ();        }        public static void DoSomething (string name)        {            if (name = = null)            {                throw new ArgumentException ("argument cannot be empty !");            }        }    }

Third, catch the exception

You can use Try/catch to capture and choose whether to handle exceptions, catch exceptions that do not necessarily handle exceptions, convert exceptions to another exception, or simply log exception information.

Keep in mind that the exception that is handled in the catch block must always be sorted in the order from most specific to least specific (from specific to general), which guarantees that the exception will be handled before a particular exception is passed to a catch block of a more general exception.

There are three forms of the Try/catch block: Try-catch, try-finally, try-catch-finally, and a try statement without a catch or finally block will cause a compiler error.

The code in a try statement is the code that can throw an exception, catching a particular exception and handling it. These catch blocks can have multiple, and catch blocks can be concatenated together, and if there are multiple catch blocks, the order of calculation is from the top to the bottom. However, for each exception that is thrown, only one catch block is executed.

1, good programming practice is to catch a specific type of exception, rather than catch a more general exception.

2. If the base type catch block that captures a particular type of catch block is present at the same time, the former must be before the latter, otherwise it will not compile.

    Class program    {        static void Main (string[] args)        {            dosomething (null);            Console.readkey ();        }        public static void DoSomething (string name)        {            try            {                Console.WriteLine (name);                if (name = = null)                {                    throw new ArgumentException ("Argument cannot be empty!");}            }            catch (ArgumentException ex)            {                name = "Hello";                DoSomething (name);                Console.WriteLine (ex. Message);            }            catch (Exception ex)            {                Console.WriteLine (ex. Message);            }            Finally            {            }        }    }

Iv. Custom Exception Classes

To create a user-defined exception class, you need to follow these points

1, derived from System.ApplicationException or System.Exception class.

2. Use the word "Exception" as the suffix of the custom exception name.

3. Provide at least three public functions.

4, a default constructor that does not contain parameters.

5. A constructor that can contain an exception message with only one parameter: message.

6, a constructor that can contain the exception message, and the exception reference that threw the exception, which are message and innerexception, respectively.

    public class OneException:System.ApplicationException    {public        oneexception () {} public        oneexception ( String message): base (Message) {} public        oneexception (String message,system.exception innerexception): Base ( message,innerexception) {}    }

V. the principle of exception handling

1, as far as possible by the program automatically handle exceptions. When an exception occurs, the program should try to handle the exception after it has been captured, and if the error is sorted, the program can return to normal, instead of notifying the user immediately when the exception is caught, or simply logging the exception information. For example, network transfer has a connection error, should be re-connected a few times before notifying the user processing.

2, limit the scope of the exception, should try to reduce the scope of the exception processing, if you only need to detect a line of code may be an exception, do not put the entire code into the try statement block.

3. More specific exceptions should be caught. Try to avoid direct capture of exception anomalies.

4. Catch and handle exceptions as much as possible on the upper layer.

5, the exception information should be stored in the log.

Suddenly recalled a piece of code from the last interview:

    Class program    {        static void Main (string[] args)        {            String name = GetName ();            Console.WriteLine (name);                       Output even if the return of this line will also be executed Oh! Output Hello            console.readkey ();        }        public static string GetName ()        {            try            {                return "Hello";            }            catch (Exception ex)            {                return "catch to Exception!";            }            Finally            {                Console.WriteLine ("Even if the return of this line will be executed Oh!") ");            }        }    }

Notice that when the exception is not thrown and return also executes the code in the finally.

Exception Handling Exception

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.