Exception trapping mechanism in C # (try Catch finally)

Source: Internet
Author: User
Tags mul throw exception try catch

First, the exception handling of C # uses the keyword

try : Used to check for exceptions that occur and to help send any possible exceptions.


catch : Handles errors in a more controlled manner, and can have multiple catch clauses.


finally: The finally code block will be executed regardless of whether an exception is thrown.


throw: For throwing exceptions, you can throw predefined and custom exceptions.

Ii. format of C # exception handling
1    Try2      {3            //program code block;4     }5 Catch(Exception e)6    {7         //exception handling code block;8    }9  finallyTen  { One      //code block to be executed, whether or not an exception occurs; A}

Third, exception handling combat

A simple example of divisor and zero:

1  Public classDivisoriszero2 {3      Private Static voidMain ()4 {5 intDividend=Ten;6 intdivisor1=0;7 intDivisor2=5;8 intDividevalue;9 Ten Try One { ADividevalue=dividend/divisor1;//(1) -     //Dividevalue=dividend/divisor2;//(2) -System.Console.WriteLine ("dividevalue={0}", Dividevalue);//(3) This line will not be executed.  the } - Catch - { -System.Console.WriteLine ("the passed exception value is: {0}", e); + } - finally + { ASystem.Console.WriteLine ("I will show you whether or not an exception occurred. "); at } - } -}

Note: (1) An exception is thrown if the row is executed, and if there is no catch statement, the program terminates abnormally, using a catch clause without parameters, you can catch any type of exception.
If the (1) line is commented out, the (2) line is enabled, which means that the program runs without an exception, and from the output, the finally code block will still be executed.

You can provide multiple catch statements to a try statement to catch a specific exception, as in the previous example: 0 as a divisor throws an exception of type DivideByZeroException, and the catch statement in the previous example can be modified as follows:

1 Catch(DivideByZeroException e)2 {3System.Console.WriteLine ("0 cannot be a divisor! The exception value is: \n{0}", e);4 }5 Catch(Exception e)6 {7System.Console.WriteLine ("not \ ' 0 exception thrown as divisor \ '! Exception value: \n{0}", e);8}

Why add a catch (Exception e) clause? The reason is simple, the catch (dividebyzeroexception e) clause catches only a specific exception, and the program code inside the try may also produce other exceptions that can only be caught by catch (Exception e).

The following table shows some common exceptions:

Common exception classes in the System namespace

Exception class name Simple description

Memberaccessexception Access Error: Type member cannot be accessed

ArgumentException parameter error: Invalid parameter for method

The ArgumentNullException parameter is empty: an unacceptable null argument is passed to the method

ArithmeticException Mathematical calculation error: Due to the mathematical operation caused by the anomaly, wide coverage.

ArrayTypeMismatchException Array Type mismatch

DivideByZeroException was 0 apart

The FormatException parameter is not properly formatted

IndexOutOfRangeException Index is out of range, less than 0 or larger than the last element's index

InvalidCastException illegal coercion, thrown when an explicit conversion fails

MulticastNotSupportedException Unsupported Multicast: Thrown when combining two non-null delegates failed

The method called by NotSupportedException is not implemented in the class

NullReferenceException when referencing a null reference object

OutOfMemoryException thrown when memory cannot be allocated for new statements, not enough memory

OverflowException Overflow

StackOverflowException Stack Overflow

TypeInitializationException the initialization type of the error: thrown when a static constructor has a problem

NotFiniteNumberException Infinite Value: The number is not legal

Iv. defining your own exception classes

In addition to the predefined exceptions, we can create our own exceptions, and the process is relatively straightforward:

One declares an exception, in the following format:

Class exceptionname:exception{}

Two throws their own exception:

throw (Exceptionname);

See an example:

1 classiamsecondgrade:system.exception{}//declaring exceptions2 3 classSecondgrade4 {5  Public Static intMulintFirstintsecond)6 {7 if(first> -|| Second> -)8 Throw NewIamsecondgrade ();//Throw Exception9 return(first*second);Ten } One  A  Public Static voidMain () - { - intMul_value; the  - Try - { -Mul_value=mul ( About, About); +System.Console.WriteLine ("99 and 56 product: {0}", mul_value); -Mul_value=mul (101,4); +System.Console.WriteLine ("An exception occurs, and this line is not executed. "); A } at Catch(Iamsecondgrade)//capturing a custom exception - { -System.Console.WriteLine ("I'm in second grade, over 100 multiplication. Hey, I'm customizing the exception. "); - } - Catch(System.Exception e) - { inSystem.Console.WriteLine ("non-custom exception. The value is: {0}", e); - } to } +}

Exception trapping mechanism in C # (try Catch finally)

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.