Summary and Simple Example of C Exception Handling

  • 2021-12-19 06:31:00
  • OfStack

Summary and Simple Example of C # Exception Handling

1. Understanding of exception handling?

Exception handling refers to the program in the process of running, errors will cause the program to exit, this kind of error, is called exception.

Therefore, handling such errors is called exception handling.

2. How does exception handling work?

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

1. try: An try block identifies a code block for 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 denotes the catch of exceptions.

3. finally: The finally block is used to execute a given statement, whether or not an exception is thrown.

For example, if you open a file, the file will be closed regardless of whether there is an exception or not.

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

Syntax example:


try

{

  //  Statement causing exception 

}

catch( ExceptionName e1 )

{

  //  Error handling code 

}

catch( ExceptionName e2 )

{

  //  Error handling code 

}

catch( ExceptionName eN )

{

  //  Error handling code 

}

finally

{

  //  Statement to execute 

}

3. Exception classes in C #

C # exceptions are represented using classes. The exception classes in C # are mainly derived directly or indirectly from System. Exception

(1). Exception types derived from System. SystemException:

System. AccessViolationException Exception thrown when attempting to read or write protected memory.

System. ArgumentException Exception thrown when one of the parameters supplied to the method is invalid.

System. Collections. Generic. KeyNotFoundException specifies the exception that is thrown when the key used to access an element in the collection does not match any of the keys in the collection.

System. IndexOutOfRangeException Exception thrown when an array is accessed because the element index exceeds the bounds of the array.

System. InvalidCastException Exception thrown due to invalid type conversion or display conversion.

System. InvalidOperationException the exception that is thrown when the method call is not valid for the current state of the object.

System. InvalidProgramException Exception thrown when a program contains invalid Microsoft intermediate language (MSIL) or metadata, which usually indicates that bug is in the compiler that generated the program.

System. IO. IOException Exception thrown when an I/O error occurs.

System. NotImplementedException Exception thrown when the requested method or operation cannot be implemented.

System. NullReferenceException Exception thrown when an attempt is made to operate on an empty object reference.

System. Exception thrown when OutOfMemoryException does not have enough memory to continue execution of the program.

System. StackOverflowException Exception thrown when an execution stack overflows due to too many pending method calls.

(2). Exception types derived from System. ArgumentException:

System. ArgumentNullException the exception thrown when a null reference is passed to a method that does not accept it as a valid parameter.

System. ArgumentOutOfRangeException the exception thrown when the parameter value exceeds the allowable value defined by the called method.

(3). Exception types derived from System. ArithmeticException:

System. DivideByZeroException Exception thrown when an attempt is made to divide an integer value or a decimal value by zero.

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

System. OverflowException Exception thrown when an arithmetic operation, type conversion, or conversion operation in the selected context causes an overflow.

(4). Exception types derived from System. IOException:

System. IO. DirectoryNotFoundException Exception thrown when a file or part 1 of a directory cannot be found.

System. IO. DriveNotFoundException Exception thrown when the drive or share you are trying to access is unavailable.

System. IO. EndOfStreamException Exception thrown when a read operation attempts to exceed the end of the stream.

System. IO. FileLoadException Exception thrown when a managed program is found but cannot be loaded.

System. IO. FileNotFoundException Exception thrown when an attempt to access a file that does not exist on disk fails.

System. IO. PathTooLongException Exception thrown when the path name or file name exceeds the maximum length defined by the system.

(5). Other common exception types:

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

The format of BadImageFormatException graphic is incorrect.

DivideByZeroException divide-by-zero exception.

DllNotFoundException could not find the referenced dll.

The FormatException parameter is in the wrong format.

MethodAccessException attempts to access private or protected methods.

MissingMemberException accessed an invalid version of dll.

The method called by NotSupportedException is not implemented in the class.

This error is thrown when a particular property is not supported on the PlatformNotSupportedException platform.

4. Examples


class MyExceptionTest

{

  static double SafeDivision(double x, double y)

  {

    if (y == 0)

      throw new System.DivideByZeroException();

    return x / y;

  }

  static void Main()

  {

    double a = 98, b = 0;

    double result = 0;

    try

    {

      result = SafeDivision(a, b);

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

    }

    catch (DivideByZeroException e)

    {

      Console.WriteLine("Attempted divide by zero.");

    }

  }

}

Thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: