Class System.Exception

Namespace: System

Represents errors that occur during code execution. This is the base class for all user-defined and run-time exceptions.

Constructors

Properties

Methods

Remarks

The Exception class is the base class for all exceptions in the .NET Framework. Exceptions are used to signal that errors have occurred during the execution of a program. When an error occurs, an exception is thrown. If the exception is not handled, the program will terminate.

You can catch exceptions using the try-catch block. The catch block specifies the type of exception that it can handle. If an exception is thrown, the .NET runtime will search for a matching catch block. If a match is found, the code in the catch block will be executed.

Example

try { // Code that might throw an exception int result = 10 / 0; } catch (DivideByZeroException ex) { // Handle the DivideByZeroException Console.WriteLine($"An error occurred: {ex.Message}"); Console.WriteLine($"Stack trace: {ex.StackTrace}"); } catch (Exception ex) { // Handle any other exceptions Console.WriteLine($"An unexpected error occurred: {ex.Message}"); }