Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

C# Dictionary

  1. Home
  2. C# Dictionary
  3. throw / Custom Exceptions

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 / MemberDescription
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.
ExceptionThe base class for all exceptions.
ArgumentExceptionThrown when an argument is invalid.
ArgumentNullExceptionThrown when an argument is null.
InvalidOperationExceptionThrown when an operation is invalid for the current state of an object.
NotImplementedExceptionUsed 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 .