How to Throw Exception in C#: Simple Guide with Examples
In C#, you throw an exception using the
throw keyword followed by an exception object, like throw new Exception("Error message"). This stops normal program flow and signals an error that can be caught and handled elsewhere.Syntax
The basic syntax to throw an exception in C# uses the throw keyword followed by a new exception object. You create the exception with new and specify the type and message.
throw: keyword to raise an exceptionnew ExceptionType("message"): creates the exception object with a message
csharp
throw new Exception("This is an error message.");
Example
This example shows how to throw an exception when a number is negative. The exception stops the program and prints the error message.
csharp
using System; class Program { static void CheckNumber(int number) { if (number < 0) { throw new ArgumentException("Number cannot be negative."); } Console.WriteLine($"Number {number} is valid."); } static void Main() { try { CheckNumber(5); CheckNumber(-3); } catch (ArgumentException ex) { Console.WriteLine($"Caught exception: {ex.Message}"); } } }
Output
Number 5 is valid.
Caught exception: Number cannot be negative.
Common Pitfalls
Common mistakes when throwing exceptions include:
- Throwing
nullinstead of an exception object causes a runtime error. - Not providing a meaningful message makes debugging harder.
- Throwing exceptions without catching them can crash the program unexpectedly.
Always throw a new exception object with a clear message and handle it properly.
csharp
/* Wrong way: throwing null */ // throw null; // This causes a runtime error /* Right way: throwing an exception object */ throw new InvalidOperationException("Invalid operation occurred.");
Quick Reference
Remember these tips when throwing exceptions in C#:
- Use
throw new ExceptionType("message")to create and throw exceptions. - Choose the most specific exception type available (e.g.,
ArgumentException,InvalidOperationException). - Always provide a clear, helpful message.
- Use
try-catchblocks to handle exceptions gracefully.
Key Takeaways
Use the throw keyword with a new exception object to raise errors in C#.
Always provide a clear message to explain the error.
Catch exceptions with try-catch blocks to prevent program crashes.
Avoid throwing null or non-exception objects.
Pick the most specific exception type for clarity and better error handling.