SoFunction
Updated on 2025-03-07

Brief analysis of how to create user-defined exceptions using C#

Overview

Exceptions are problems that occur during program execution. Exceptions in C# are a response to special circumstances that occur when the program is running, such as trying 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 code block of a specific exception to be activated. Followed by one or more catch blocks. catch: The program catches exceptions through exception handlers. The catch keyword indicates the capture of an exception. finally: The 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 it occurs. throw: When the problem occurs, the program throws an exception. Use the throw keyword to do it.

Custom exceptions

You can also define your own exceptions. User-defined exception classes are derived from ApplicationException classes.

using System;
namespace UserDefinedException
{
   class TestTemperature
   {
      static void Main(string[] args)
      {
         Temperature temp = new Temperature();
         try
         {
            ();
         }
         catch(TempIsZeroException e)
         {
            ("TempIsZeroException: {0}", );
         }
         ();
      }
   }
}
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
      {
         ("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 the 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
}

Summarize

This is the end of this article about how to create user-defined exceptions with C#. For more relevant C# user-defined exception content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!