C # preliminary Exception Handling Mechanism

Source: Internet
Author: User

I learned the Exception Handling Mechanism of C # today. I will summarize it as follows:


I. keywords used for exception handling in C #


Try is used to check for exceptions and help send any possible exceptions.


Catch handles errors in a way with greater control. There can be multiple catch clauses.


Whether or not an exception occurs, the finally code block is executed.


Throw is used to cause exceptions. It can cause pre-defined exceptions and custom exceptions.


II. C # Exception Handling Format


Try


{


Program code block;


}


Catch (Exception e)


{


Exception Handling Code block;


}


Finally


{


The code block to be executed no matter whether an exception occurs;


}



Iii. Exception handling practices


A simple example of division and zero:


Public class DivisorIsZero


{


Private static void Main ()


{


Int dividend = 10;


Int divisor1 = 0;


Int divisor2 = 5;


Int DivideValue;


Try


{


DivideValue = dividend/divisor1; // (1)


// DivideValue = dividend/divisor2; // (2)


System. Console. WriteLine ("DivideValue = {0}", DivideValue); // (3) this line will not be executed.


}


Catch


{


System. Console. WriteLine ("passed abnormal values: {0}", e );


}


Finally


{


System. Console. WriteLine ("no matter whether an exception occurs, I will display it. ");


}


}


}



Note: (1) If a row is executed, an exception is thrown. If no catch statement is available, the program terminates abnormally. If a catch clause without parameters is used, any types of exceptions can be caught.


If line (1) is commented out and line (2) is enabled, this means that the program runs without exceptions. The finally code block will still be executed from the output.



Multiple catch statements can be provided for the try statement to catch specific exceptions. In the preceding example, 0 is used as the DivideByZeroException type, and the catch statement in the preceding example can be modified as follows:


Catch (DivideByZeroException e)


{


System. Console. WriteLine ("zero cannot be used as the divisor! Abnormal Values: {0} ", e );


}


Catch (Exception e)


{


System. Console. WriteLine ("non-zero as the divisor exception \"! Abnormal Values: {0} ", e );


}


Why should I add a catch (Exception e) clause? The cause is very simple. The catch (DivideByZeroException e) clause can only catch specific exceptions. program code in try may also produce other exceptions. These exceptions can only be caught (Exception e).


The following table shows some common exceptions:



Common exception classes in the System namespace



Brief description of exception class name


MemberAccessException access error: type members cannot be accessed


ArgumentException parameter error: the method parameter is invalid.


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


ArithmeticException: A mathematical error occurs because of mathematical operations, which has a wide coverage.


ArrayTypeMismatchException array Type Mismatch


DivideByZeroException is divided by zero


The FormatException parameter format is incorrect.


The IndexOutOfRangeException index is out of the range. It is smaller than 0 or greater than the index of the last element.


The InvalidCastException is invalid and is thrown when the explicit conversion fails.


Multicast not supported by MulticastNotSupportedException: triggered when two non-empty delegation fails to be combined


The method called by NotSupportedException is not implemented in the class.


Thrown when NullReferenceException references an empty referenced object


OutOfMemoryException is caused when the memory cannot be allocated for the new statement, and the memory is insufficient.


OverflowException Overflow


StackOverflowException Stack Overflow


Incorrect TypeInitializationException initialization type: caused by a problem with the static Constructor


NotFiniteNumberException: The number is invalid.



4. define your own exception classes


In addition to predefined exceptions, we can also create our own exceptions. The process is relatively simple:


(I) declare an exception in the following format:


Class ExceptionName: Exception {}


(Ii) Exceptions:


Throw (ExceptionName );



Let's look at an example:


Class IAmSecondGrade: System. Exception {} // declare an Exception



Class SecondGrade


{


Public static int mul (int first, int second)


{


If (first> 100 | second> 100)


Throw new IAmSecondGrade (); // raises an exception


Return (first * second );


}



Public static void Main ()


{


Int mul_value;


Try


{


Mul_value = mul (99,56 );


System. Console. WriteLine ("99 and 56 product: {0}", mul_value );


Mul_value = mul (10 );


System. Console. WriteLine ("this line will not be executed if an exception occurs. ");


}


Catch (IAmSecondGrade) // catch custom exceptions


{


System. Console. WriteLine ("I'm in the second grade. I won't use more than 100 multiplication. Hey, my custom exception. ");


}


Catch (System. Exception e)


{


System. Console. WriteLine ("non-custom exception. The value is {0} ", e );


}



}


}



Today, we have learned some important features of exception handling, and many other features that need further efforts.


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.