C # Basic point of Try catch exception trapping mechanism

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

  1. First, the exception handling of C # uses the keyword
  2. Try is used to check for exceptions that occur and to help send any possible exceptions.
  3. Catch handles errors in a much more controlled manner, and can have multiple catch clauses.
  4. Finally whether or not an exception is thrown,finally the code block will be executed.
  5. Throw is used to throw exceptions, which can throw predefined and custom exceptions.
  6. Ii. format of C # exception handling
  7. Try
  8. {
  9. program code block;
  10. }
  11. catch (Exception e)
  12. {
  13. Exception handling code block;
  14. }
  15. Finally
  16. {
  17. code block to be executed, whether or not an exception occurs;
  18. }
  19. Third, exception handling combat
  20. A simple example of divisor and zero:
  21. Public class Divisoriszero
  22. {
  23. Private static void Main ()
  24. {
  25. int dividend=10;
  26. int divisor1=0;
  27. int divisor2=5;
  28. int dividevalue;
  29. Try
  30. {
  31. Dividevalue=dividend/divisor1; //(1)
  32. Dividevalue=dividend/divisor2; (2)
  33. System.Console.WriteLine ("dividevalue={0}", Dividevalue);   (3) This line will not be executed.
  34. }
  35. Catch
  36. {
  37. System.Console.WriteLine ("passed the exception value is: {0}", e);
  38. }
  39. Finally
  40. {
  41. System.Console.WriteLine ("I will show whether or not an exception occurred.)  ");
  42. }
  43. }
  44. }
  45. 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.
  46. 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, thefinally code block will still be executed.
  47. 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:
  48. catch (DivideByZeroException e)
  49. {
  50. System.Console.WriteLine ("0 cannot be a divisor!")  The exception value is: \n{0} ", E);
  51. }
  52. catch (Exception e)
  53. {
  54. System.Console.WriteLine ("not \ ' 0 exception thrown by divisor \"! Exception value: \n{0} ", E);
  55. }
  56. Why add a catch (Exception e) clause?  The reason is simple, thecatch (dividebyzeroexception e) clause catches only a specific exception, andthe program code inside the try may also produce other exceptions that can only be caught by catch (Exception e).
  57. The following table shows some common exceptions:
  58. Common exception classes in the System namespace
  59. Exception class name Simple description
  60. Memberaccessexception Access Error: Type member cannot be accessed
  61. ArgumentException parameter error: Invalid parameter for method
  62. The ArgumentNullException parameter is empty: an unacceptable null argument is passed to the method
  63. ArithmeticException Mathematical calculation error: Due to the mathematical operation caused by the anomaly, wide coverage.
  64. ArrayTypeMismatchException Array Type mismatch
  65. DivideByZeroException was 0 apart
  66. The FormatException parameter is not properly formatted
  67. IndexOutOfRangeException Index is out of range, less than 0 or larger than the last element's index
  68. InvalidCastException illegal coercion, thrown when an explicit conversion fails
  69. MulticastNotSupportedException Unsupported Multicast: Thrown when combining two non-null delegates failed
  70. The method called by NotSupportedException is not implemented in the class
  71. NullReferenceException when referencing a null reference object
  72. OutOfMemoryException thrown when memory cannot be allocated for new statements, not enough memory
  73. OverflowException Overflow
  74. StackOverflowException Stack Overflow
  75. TypeInitializationException the initialization type of the error: thrown when a static constructor has a problem
  76. NotFiniteNumberException Infinite Value: The number is not legal
  77. Iv. defining your own exception classes
  78. In addition to the predefined exceptions, we can create our own exceptions, and the process is relatively straightforward:
  79. One declares an exception, in the following format:
  80. Class exceptionname:exception{}
  81. Two throws their own exception:
  82. throw (Exceptionname);
  83. See an example:
  84. Class iamsecondgrade:system.exception{}//declaring exceptions
  85. Class Secondgrade
  86. {
  87. Public static int mul (int First,int second)
  88. {
  89. if (first>100| | SECOND>100)
  90. Throw new Iamsecondgrade (); Throw Exception
  91. return (First*second);
  92. }
  93. Public static void Main ()
  94. {
  95. int mul_value;
  96. Try
  97. {
  98. Mul_value=mul (99,56);
  99. System.Console.WriteLine ("99 and 56 product: {0}", Mul_value);
  100. Mul_value=mul (101,4);
  101. System.Console.WriteLine ("There is an exception, this line will not be executed.")  ");
  102. }
  103. catch (Iamsecondgrade)//Capture Custom exceptions
  104. {
  105. System.Console.WriteLine ("I'm only in second grade, over 100 multiplication I won't. Hey, I'm customizing the exception.  ");
  106. }
  107. catch (System.Exception e)
  108. {
  109. System.Console.WriteLine ("Non-custom exception.  The value is: {0} ", e);
  110. }
  111. }
  112. }

C # Basic point of Try catch exception trapping mechanism

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.