throw / Custom Exceptions
The throw keyword intentionally raises an exception, and a custom exception class lets you carry application-specific error information.
Syntax
// Throw an exception.
throw new ExceptionType("message");
// Define a custom exception class.
class ClassName : Exception
{
public ClassName(string message) : base(message) { }
}
Syntax / Members
| Syntax / Member | Description |
|---|---|
| throw new Exception("msg") | Throws an exception. Interrupts the current method call and transfers control to the nearest catch block. |
| throw; | Used inside a catch block to rethrow the caught exception while preserving the original stack trace. |
| Exception | The base class for all exceptions. |
| ArgumentException | Thrown when an argument is invalid. |
| ArgumentNullException | Thrown when an argument is null. |
| InvalidOperationException | Thrown when an operation is invalid for the current state of an object. |
| NotImplementedException | Used to indicate that a method has not been implemented yet. |
Sample Code
using System;
// Throw an exception with throw.
void CheckAge(int age)
{
if (age < 0 || age > 150) {
throw new ArgumentOutOfRangeException(nameof(age), "Age must be between 0 and 150.");
}
Console.WriteLine($"Age: {age}");
}
try {
CheckAge(200);
} catch (ArgumentOutOfRangeException e) {
Console.WriteLine(e.Message);
}
// Define a custom exception class.
class AppException : Exception
{
public int StatusCode { get; }
public AppException(string message, int statusCode) : base(message)
{
StatusCode = statusCode;
}
}
// Throw and catch a custom exception.
try {
throw new AppException("Authentication failed.", 401);
} catch (AppException e) {
Console.WriteLine($"[{e.StatusCode}] {e.Message}");
}
// Rethrow inside a catch block (preserves the stack trace).
void Process()
{
try {
int result = int.Parse("abc");
} catch (FormatException) {
Console.WriteLine("Log: Conversion error detected.");
throw; // Rethrow the exception.
}
}
try {
Process();
} catch (FormatException e) {
Console.WriteLine("Caught at upper level: " + e.Message);
}
Details
A custom exception class is defined by inheriting from Exception (or another existing exception class). Adding application-specific error codes or extra information as properties enables more detailed error handling in the catch block.
When rethrowing, writing throw e; overwrites the stack trace with the current position. Use the argument-less throw; when you want to preserve the original stack trace.
For the exception-catching syntax, see try / catch / finally.
If you find any errors or copyright issues, please contact us.