C# Tutoriallogin
C# Tutorial
author:php.cn  update time:2022-04-11 14:06:23

C# exception handling



Exceptions are problems that occur during program execution. An exception in C# is a response to a special situation that occurs while the program is running, such as an attempt to divide by zero.

Exceptions provide a way to transfer program control from one part to another. C# exception handling is based on four keywords: try, catch, finally and throw.

  • try: A try block identifies a block of code that will be activated for a specific exception. Followed by one or more catch blocks.

  • catch: The program catches exceptions through exception handlers. The catch keyword indicates exception catching.

  • finally: The finally block is used to execute a given statement, regardless of whether an exception is thrown. For example, if you open a file, the file will be closed regardless of whether an exception occurs.

  • throw: When a problem occurs, the program throws an exception. Use the throw keyword to accomplish this.

Syntax

Suppose a block will throw an exception and a method catches the exception using the try and catch keywords. The code within the try/catch block is protected code. The try/catch syntax is as follows:

try
{
   // 引起异常的语句
}
catch( ExceptionName e1 )
{
   // 错误处理代码
}
catch( ExceptionName e2 )
{
   // 错误处理代码
}
catch( ExceptionName eN )
{
   // 错误处理代码
}
finally
{
   // 要执行的语句
}

You can list multiple catch statements to capture different types of exceptions to prevent the try block from running in different Multiple exceptions are generated in this case.

Exception classes in C

#C# Exceptions are represented by classes. The exception classes in C# are mainly derived directly or indirectly from the System.Exception class. The System.ApplicationException and System.SystemException classes are exception classes derived from the System.Exception class.

System.ApplicationException Class supports exceptions generated by applications. Therefore, all exceptions defined by the programmer should be derived from this class.

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

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

Exception classDescription
System.IO.IOExceptionHandle I/O errors.
System.IndexOutOfRangeExceptionHandle the error generated when a method points to an array index that is out of range.
System.ArrayTypeMismatchExceptionHandles errors generated when array types do not match.
System.NullReferenceExceptionHandle errors generated when conforming to a null object.
System.DivideByZeroExceptionHandle the error generated when dividing by zero.
System.InvalidCastExceptionHandle errors generated during type conversion.
System.OutOfMemoryExceptionHandle errors generated by insufficient free memory.
System.StackOverflowExceptionHandle errors generated by stack overflow.

Exception handling

C# provides a structured exception handling scheme in the form of try and catch blocks. Use these blocks to separate core program statements from error handling statements.

These error handling blocks are implemented using the try, catch and finally keywords. The following is an example of an exception being thrown when dividing 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(25, 0);
            Console.ReadKey();
        }
    }
}

When the above code is compiled and executed, it will produce 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 classes are 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

Throws the object

If the exception is You can throw an object that is derived directly or indirectly from the System.Exception class. You can throw the current object using a throw statement in a catch block as follows:

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

php.cn