C # exception handling

Source: Internet
Author: User
Tags finally block

An exception is an issue that occurs during program execution. Exceptions in C # are a response to special situations that occur when a program runs, such as trying to divide by 0.

Exceptions provide a way to transfer control of a program from one part to another.

C # exception handling is built on four keywords:try,catch,finally , and throw.

    • try: a try block identifies a block of code that will be activated for a particular exception. followed by one or more catch blocks.
    • Catch: The program catches exceptions through an exception handler. The Catch keyword represents the catch of the exception.
    • finally: the finally block is used to execute the given statement, regardless of whether the exception is thrown. For example, if you open a file, it will be closed regardless of whether the exception file appears.
    • throw: When the problem occurs, the program throws an exception. Use the Throw keyword to complete.
Grammar

Suppose a block will have an exception, and a method catches the exception using the try and catch keywords. The code inside the Try/catch block is protected code, using the Try/catch syntax as follows:

Try{   Block of statements that cause exceptions}Catch( ExceptionnameE1){ Error handling code block 1}catch (  Exceptionname E2 ) { Span class= "com" >//error handling code block 2}catch ( exceptionname EN ) { //error handling code block N }finally{//statement to execute (whether or not an exception is triggered) }        

You can list multiple catch statements to catch different types of exceptions in case the try block generates multiple exceptions in different situations.

exception classes in C #

C # Exceptions are represented by using classes. Exception classes in C # are primarily derived directly or indirectly from the System.Exception class. The system.applicationexception and system.systemexception classes are exception classes that derive from the System.Exception class.

The system.applicationexception class supports exceptions generated by the application. So a programmer-defined exception should derive from that class.

The system.systemexception class is the base class for all predefined system exceptions.

The following table lists some of the pre-defined exception classes derived from the Sytem.systemexception class:

Exception Class Description
System.IO.IOException Handles I/O errors.
System.IndexOutOfRangeException Handles errors that are generated when a method points to an array index that is out of range.
System.ArrayTypeMismatchException Handles errors that are generated when the array type does not match.
System.NullReferenceException Handles errors that are generated when an empty object is complied with.
System.DivideByZeroException Handles the error generated when dividing by zero.
System.InvalidCastException Handles errors that are generated during type conversion.
System.OutOfMemoryException Handles errors generated by insufficient free memory.
System.StackOverflowException Handles the error generated by the stack overflow.
Exception Handling

C # provides a structured exception handling scheme in the form of try and catch blocks. Use these blocks to divide the core program statements from the error handling statements.

These error-handling blocks are implemented using the try,catch , and finally keywords. The following is an instance that throws an exception when divided by zero:

1 usingSystem;2 namespaceerrorhandlingapplication3 {4     classdivnumbers5     {6         intresult;7 divnumbers ()8         {9result =0;Ten         } One          Public voidDivision (intNUM1,intnum2) A         { -             Try -             { theresult = NUM1/num2; -             } -             Catch(DivideByZeroException e) -             { +Console.WriteLine ("Exception caught: {0}", e); -             } +             finally A             { atConsole.WriteLine ("Result: {0}", result); -             } -  -         } -         Static voidMain (string[] args) -         { inDivnumbers d =Newdivnumbers (); -D.division ( -,0); to Console.readkey (); +         } -     } the}

When the above code is compiled and executed, it produces the following results:

Exception caught:System.DivideByZeroException:Attempted to divide by zero. At ... result:0
Create a user-defined exception

You can also define your own exceptions. The user-defined exception class is derived from the ApplicationException class. The following example demonstrates this:

1 usingSystem;2 namespaceuserdefinedexception3 {4    classtesttemperature5    {6       Static voidMain (string[] args)7       {8Temperature temp =Newtemperature ();9          TryTen          { One temp.showtemp (); A          } -          Catch(tempiszeroexception e) -          { theConsole.WriteLine ("tempiszeroexception: {0}", e.message); -          } - Console.readkey (); -       } +    } - } +  Public classtempiszeroexception:applicationexception A { at     PublicTempiszeroexception (stringMessage):Base(message) -    { -    } - } -  Public classTemperature - { in    intTemperature =0; -     Public voidshowtemp () to    { +       if(Temperature = =0) -       { the          Throw(NewTempiszeroexception ("Zero temperature found")); *       } $       ElsePanax Notoginseng       { -Console.WriteLine ("temperature: {0}", temperature); the       } +    } A}

When the above code is compiled and executed, it produces the following results:

Tempiszeroexception:zero Temperature found

Throwing Objects

If the exception is derived directly or indirectly from the System.Exception class, you can throw an object. You can use the throw statement in a catch block to throw the current object, as follows:

Catch (Exception e) {   ...   Throw e}

C # exception handling

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.