C # Tutorial C # exception handling

Source: Internet
Author: User
Tags finally block

C # exception handling

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.

The finally:finally block is used to execute a 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{   //Cause exception Statement}catch (Exceptionname E1) {   //Error handling code}catch (exceptionname E2) {   //Error handling code}catch ( Exceptionname EN) {   //error handling code}finally{   //statement to execute}

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

Describe

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.

The 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 errors that are generated when divided by zero.

System.InvalidCastException handles errors that are generated during type conversion.

System.OutOfMemoryException handles errors generated by insufficient free memory.

System.StackOverflowException processing stack Overflow generated errors.

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:

Using System;namespace errorhandlingapplication{    class divnumbers    {        int result;        Divnumbers ()        {            result = 0;        }        public void Division (int num1, int num2)        {            try            {                result = num1/num2;            }            catch (DivideByZeroException e)            {                Console.WriteLine ("Exception caught: {0}", e);            }            Finally            {                Console.WriteLine ("Result: {0}", result);            }        }        static void Main (string[] args)        {            divnumbers d = new Divnumbers ();            D.division (0);            Console.readkey ();}}}    

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:

Using System;namespace userdefinedexception{   class testtemperature   {      static void Main (string[] args)      {         Temperature temp = new temperature ();         Try         {            temp.showtemp ();         }         catch (tempiszeroexception e)         {            Console.WriteLine ("Tempiszeroexception: {0}", e.message);         }         Console.readkey ();}}}   public class tempiszeroexception:applicationexception{Public   tempiszeroexception (String message): Base ( Message)   {   }}public class temperature{   int temperature = 0;   public void Showtemp ()   {      if (temperature = = 0)      {         throw (new Tempiszeroexception ("Zero temperature Found "));      }      else      {         Console.WriteLine ("Temperature: {0}", temperature);      }   }

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}

Above is the "C # Tutorial" C # Exception handling content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.