Preliminary study on C # exception handling mechanism

Source: Internet
Author: User
Tags exception handling mul
Exception handling today learned the C # exception handling mechanism, is summarized as follows:

Keywords used in C # 's exception handling

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

Catch handles errors in a much more controlled way, and can have multiple catch clauses.

Finally, whether or not an exception is thrown, the finally code block is executed.

Throw is used to throw exceptions, which can throw predefined exceptions and custom exceptions.

Second, C # exception handling format

Try

{

program code block;

}

catch (Exception e)

{

Exception handling code block;

}

Finally

{

A block of code to execute, regardless of whether an exception occurred;

}



Third, the abnormal treatment of actual combat

A simple example of divisor 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 ("Pass over the exception value is: {0}", e);

}

Finally

{

System.Console.WriteLine ("I will show you whether or not an exception occurs.") ");

}

}

}



Note: (1) If the row is executed, an exception is thrown, and if there are no catch statements, the program terminates abnormally, using a catch clause with no parameters, you can catch any type of exception.

If the (1) line is commented out and the (2) row is enabled, this means that the program will run without an exception, from the output that 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 example above: 0 throws a DivideByZeroException type exception, and the catch statement in the example above can be modified as follows:

catch (DivideByZeroException e)

{

System.Console.WriteLine ("0 cannot be a divisor!") The exception value is: \n{0} ", E);

}

catch (Exception e)

{

System.Console.WriteLine ("not \ ' 0 is the exception that is thrown by divisor \"! Exception value is: \n{0} ", E);

}

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

Some common exceptions are given in the following table:



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

ArgumentNullException parameter is null: pass an unacceptable null parameter to the method

ArithmeticException Mathematical calculation error: Due to mathematical operations caused by the exception, wide coverage.

ArrayTypeMismatchException array types do not match

DivideByZeroException by 0 apart

FormatException parameter is not in the correct format

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

InvalidCastException illegal casts that are thrown when an explicit conversion fails

MulticastNotSupportedException Multicast not supported: Raised when two non-null delegates failed

The method called by NotSupportedException is not implemented in the class

NullReferenceException when referencing an empty reference object

OutOfMemoryException failed to allocate memory for new statement, not enough memory

OverflowException Overflow

StackOverflowException Stack Overflow

Initialization type for TypeInitializationException 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 simple:

㈠ declares an exception with the following format:

Class exceptionname:exception{}

㈡ throws its own exception:

throw (Exceptionname);



Look at an example:

Class iamsecondgrade:system.exception{}//Declaration exception



Class Secondgrade

{

public static int Mul (int first,int second)

{

if (first>100| | SECOND>100)

throw new Iamsecondgrade ()//Throw 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 is: {0}", Mul_value);

Mul_value=mul (101,4);

System.Console.WriteLine ("An exception occurs, this line is not executed.) ");

}

catch (Iamsecondgrade)//Catch a custom exception

{

System.Console.WriteLine ("I'm only in grade two, more than 100 multiplication I won't.") Hey, I'm customizing the exception. ");

}

catch (System.Exception e)

{

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

}



}

}



Today, we learned some important characteristics of exception handling, and many other features, which need to be worked out



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.