Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

The exception handling of the C#


May 11, 2021 C#


Table of contents


The C#exception handling

An exception is a problem that occurs during program execution. Exceptions in C# are a response to special situations that occur when a program is running, such as trying to divide by zero.

Exceptions provide a way to transfer program control from one part to another. Exception handling is based on four key words: try, catch, finally, and throw.

  • Try: A try block identifies a block of code for a specific exception that will be activated. This is followed by one or more catch blocks.
  • catch: The program catches the exception through the exception handler. The catch keyword represents the catch of an exception.
  • The final:finally block is used to execute a given statement, regardless of whether the exception is thrown or not. 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 do this.

Grammar

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

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

You can list multiple catch statements to catch different types of exceptions in case the try block generates multiple exceptions in different situations.

The exception class in C#

The exception is represented by a class. T he exception class in C# is 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.

The System.ApplicationException class supports exceptions generated by the application. Therefore, programmer-defined exceptions should be derived from the class.

The 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:

Anomaly describe
System.IO.IOException Processing an I / O error.
System.IndexOutOfRangeException Processing When the method points to an error generated by an array index of an outward range.
System.ArrayTypeMismatchException Processing errors generated when the array type does not match.
System.NullReferenceException Processing errors generated from an empty object.
System.DivideByZeroException Processing is removed by zero.
System.InvalidCastException Processing errors generated during type conversion.
System.OutOfMemoryException Handling errors generated in short memory.
System.StackOverflowException Handling the mistake of the stack.

Exception handling

A structured exception handling scheme is provided in the form of try and catch blocks. Use these blocks to part with the core program statement from the error handling statement.

These error handling blocks are implemented using the try, catch, and final keywords. Here's an example of throwing 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(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 a user-defined exception

You can also define your own exceptions. U ser-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

Throw the object

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 the catch block to throw the current object, as follows:

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