C# exception handling


Release date:2023-09-01 Update date:2023-10-13 Editor:admin View counts:278

Label:

C# exception handling

Exceptions are problems that occur during program execution. An exception inC # is a response to a special situation that occurs when the program is running, such as trying to divide by zero.

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

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

  • catch: The program catches an exception through an exception handler catch keyword indicates the catch of an exception.

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

  • throw: When a problem occurs, the program throws an exception use throw keyword to complete.

Grammar

Suppose an exception will occur in a block, and a method uses the try and catch keyword catches exceptions. The code within the try/catch block is protected code, using the try/catch syntax as follows:

try
{
   // Statement that causes an exception
}
catch( ExceptionName e1 )
{
   // Error handling code
}
catch( ExceptionName e2 )
{
   // Error handling code
}
catch( ExceptionName eN )
{
   // Error handling code
}
finally
{
   // Statement to be executed
}

You can list multiple catch statement to catch different types of exceptions to prevent try block generates multiple exceptions in different situations.

C# exception classes

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

System.ApplicationException class supports exceptions generated by the application. So all exceptions defined by programmers should be derived fromthis class.

System.SystemException class is the base class for all predefined systemexceptions.

The following table lists some predefined exception classes derivefrom the System.SystemException class:

Abnormal class

Description

System.IO.IOException

An error occurred while handling I/O.

System.IndexOutOfRangeException

Handles errors generated when a method points to an out-of-range array index.

System.ArrayTypeMismatchException

Handles errors generated when array types do not match.

System.NullReferenceException

Handles errors generated when complying with an empty object.

System.DivideByZeroException

Handles the error generated when divided by 00:00.

System.InvalidCastException

Handles errors generated during type conversion.

System.OutOfMemoryException

Handle errors generated by insufficient free memory.

System.StackOverflowException

The generated error overflowed from the processing stack.

Exception handling

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

These error handling blocks are made using the trycatch and finally keyword. The following is an example of an exception thrown whendivided by 00:00:

Example

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. User-defined exception classes are derived from the ApplicationException class. The following example demonstrates this:

Example

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 an object

If the exception is derived directly or indirectly from System.Exception class, you can throw an object. You can find it in the catch used in block throw statement to throw the current object,as follows:

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

Powered by TorCMS (https://github.com/bukun/TorCMS).