SoFunction
Updated on 2025-03-07

Summary of C# exception handling and simple examples

Summary of C# exception handling and simple examples

1. Understanding of exception handling?

Exception handling refers to an error that occurs during the program's running process, which will cause the program to exit. This kind of error is called an exception.

Therefore, handling this error is called exception handling.

2. How to handle exceptions?

C# exception handling is based on four keywords: try, catch, finally and throw.

1. try: A try block identifies a code block of a specific exception to be activated. Followed by one or more catch blocks.

2. catch: The program catches exceptions through exception handlers. The catch keyword indicates the capture of an exception.

3. 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.

4. throw: When the problem occurs, the program throws an exception. Use the throw keyword to do it.

Syntax example:

try

{

  // Statement that causes exception
}

catch( ExceptionName e1 )

{

  // Error handling code
}

catch( ExceptionName e2 )

{

  // Error handling code
}

catch( ExceptionName eN )

{

  // Error handling code
}

finally

{

  // Statement to be executed
}

3. Exception classes in C#

C# exceptions are represented by classes. Exception classes in C# are mainly derived directly or indirectly from

(1).Exception type derived:

Exception raised when trying to read and write protected memory.

Exception raised when one of the parameters provided to the method is invalid.

Specifies the exception that is thrown when the key used to access elements in the collection does not match any keys in the collection.

An exception caused by the element index exceeding the array boundary when accessing an array.

Exception caused by invalid type conversion or display conversion.

Exception raised when the method call is invalid for the current state of the object.

Exception raised when a program contains invalid Microsoft intermediate language (MSIL) or metadata, which usually indicates a bug in the compiler that generates the program.

An exception that occurs when an I/O error occurs.

Exception raised when the requested method or operation cannot be implemented.

An exception thrown when trying to operate on an empty object reference.

An exception raised when there is not enough memory to continue executing the program.

Excessive pending method calls result in exceptions raised when execution stack overflow.

(2).Exception type derived:

Exception raised when passing an empty reference to a method that does not accept it as a valid parameter.

An exception raised when the parameter value exceeds the allowed value range defined by the called method.

(3).Exception type derived:

An exception that is thrown when trying to divide an integer value or a decimal value with zero.

Exception raised when the floating point value is positive infinity, negative infinity, or non-numeric (NaN).

An exception that is raised when an arithmetic operation, type conversion, or conversion operation performed in the selected context results in an exception that overflows.

(4).Exception type derived:

Exception raised when a file or part of a directory cannot be found.

Exception thrown when the drive or share attempted to access is unavailable.

An exception raised when the read operation attempts to exceed the end of the stream.

Exception raised when a managed program is found but cannot load it.

Exception thrown when attempting to access a file that does not exist on disk fails.

Exception raised when the path name or file name exceeds the maximum length defined by the system.

(5). Other common exception types:

ArrayTypeMismatchException An attempt to store an object of the wrong type in an array.

BadImageFormatException Graphic format is wrong.

DivideByZeroException DivideByZeroException.

DllNotFoundException The referenced dll cannot be found.

FormatException parameter format is wrong.

MethodAccessException Attempt to access private or protected methods.

MissingMemberException Accesses an invalid version of the dll.

The method called NotSupportedException is not implemented in the class.

PlatformNotSupportedException This error is thrown when the platform does not support a specific property.

IV. Example

class MyExceptionTest

{

  static double SafeDivision(double x, double y)

  {

    if (y == 0)

      throw new ();

    return x / y;

  }

  static void Main()

  {

    double a = 98, b = 0;

    double result = 0;

    try

    {

      result = SafeDivision(a, b);

      ("{0} divided by {1} = {2}", a, b, result);

    }

    catch (DivideByZeroException e)

    {

      ("Attempted divide by zero.");

    }

  }

}

Thank you for reading, I hope it can help you. Thank you for your support for this site!