Represents errors that occur during code execution. This is the base class for all user-defined and run-time exceptions.
Initializes a new instance of the Exception
class.
Initializes a new instance of the Exception
class with a specified error message.
Initializes a new instance of the Exception
class with a specified error message and a reference to the inner exception that is the cause of this exception.
Gets a collection of key/value pairs that provide additional user-defined information about the exception.
Gets or sets a link to the help file that links to the help associated with this exception.
Gets or sets HRESULT, which is a numeric value that is assigned to a specific exception.
Gets a reference to the Exception
instance that causes the current exception.
Gets an error message that describes the current exception.
Gets or sets the name of the application or the object that causes the error.
Gets a string representation of the immediate frames of the call stack.
Gets the MethodBase
object that describes the currently executing stack frame.
Determines whether the specified object is equal to the current object.
When overridden in a derived class, returns the Exception
that is the root cause of the current exception.
Serves as the default hash function.
Sets the SerializationInfo
object with information about the exception.
Gets the type of the current instance.
Overrides Object.ToString
to return a string representation of the current exception.
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.
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}");
}