Latest web development tutorials

C # exception handling

Abnormalities during program execution problems. C # is an exception in response to the exceptional circumstances arising when the program runs, such as the attempt to divide by zero.

The exception is provided a program control is transferred from one part to another part of the way. C # exception handling based on the four key wordsabove:try, catch, finally andthrow.

  • try: a try block identifies the specific exception of a block of code to be activated.Followed by one or more catch blocks.
  • catch: catch the exception program through an exception handler.catch keyword indicates abnormal capture.
  • finally: finally block is used to perform a given statement, regardless of whether an exception is thrown will execute.For example, if you open a file, regardless of whether there should be an exception file is closed.
  • throw: When problems arise, the program throws an exception.Use keywords to complete the throw.

grammar

Suppose a block abnormal, a method using the keywords try and catch an exception. Code try / catch block is protected code, use try / catch as shown in the following syntax:

try
{
   } // Statement that caused the exception
catch (ExceptionName e1)
{
   // Error handling code}
catch (ExceptionName e2)
{
   // Error handling code}
catch (ExceptionName eN)
{
   // Error handling code}
finally
{
   // Statements to execute}

You can list multiple catch statements to catch different types of exceptions, to prevent the try block generates multiple exceptions under different circumstances.

Exception classes in C #

C # exception is the use of class representation. Exception classes in C # mostly directly or indirectly derived fromSystem.Exception class.System.ApplicationException andSystem.SystemExceptionclass is derived exception classes System.Exception class.

System.ApplicationException class support generated by the application exception.So the programmer-defined exceptions should be derived from this class.

System.SystemException class is all predefined system base class for exceptions.

The following table lists some derived from predefined Sytem.SystemException class exception classes:

异常类描述
System.IO.IOException处理 I/O 错误。
System.IndexOutOfRangeException处理当方法指向超出范围的数组索引时生成的错误。
System.ArrayTypeMismatchException处理当数组类型不匹配时生成的错误。
System.NullReferenceException处理当依从一个空对象时生成的错误。
System.DivideByZeroException处理当除以零时生成的错误。
System.InvalidCastException处理在类型转换期间生成的错误。
System.OutOfMemoryException处理空闲内存不足生成的错误。
System.StackOverflowException处理栈溢出生成的错误。

Exception Handling

C # to try and catch block is provided in the form of a structured exception handling program. Using these blocks, the core program statements and error handling statements separated.

Error handling these blocks is to usetry, catchandfinallykeywords to achieve. Here is an exception thrown when divided by zero Examples:

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 (25, 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 user-defined exception

You can also define your own exceptions. User-defined exception class is derived fromApplicationException class.The following example illustrates this point:

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

Throwable

If the exception is directly or indirectly derived from theSystem.Exception class, you can throw an object.You can use the catch block throw statement to throw the current object as follows:

Catch (Exception e)
{
   ...
   Throw e
}