C#
throw
Learn to throw your own exceptions with throw.
Throwing exceptions with throw
The throw keyword throws an exception. It is how you signal an unexpected or invalid condition in your program. It is usually written as throw new ExceptionType("message").
For example, if (age < 0) throw new ArgumentException("Negative age"); creates and throws a new exception when age is negative. The calling code can catch this exception with try/catch; otherwise the program crashes.
Rethrowing
If you want to forward a caught exception to an outer handler instead of handling it in the same block, use throw; (bare throw). This rethrows the exception while preserving its original stack trace, so the source of the error is not lost.
For example, in catch (Exception) { LogError(); throw; }, the error is logged first, then the exception is propagated to the caller. Writing throw ex; instead of throw; cuts the stack trace and shifts the apparent source to this line, which is usually undesirable.
Creating an exception with a message
Giving a message when you throw an exception makes the cause clear. An exception created with new Exception("message") carries the message through its Message property. When the error is caught, you can show or log this message.
For example, throw new Exception("Missing data"); throws an exception whose message is "Missing data". In a catch (Exception ex) block, ex.Message returns this string. The clearer the message, the easier the debugging.
Exercise Validate and throw
Inside the try block, throw throw new ArgumentException("Negative age"); when if (age < 0). Otherwise print the age with Console.WriteLine(age);. In the catch (ArgumentException ex) block, print Console.WriteLine(ex.Message);.
Show example solution
In the try block, write if (age < 0) throw new ArgumentException("Negative age"); else Console.WriteLine(age);
Example solution:
using System;
class Program
{
static void Main()
{
int age = -5;
try
{
if (age < 0)
{
throw new ArgumentException("Negative age");
}
Console.WriteLine(age);
}
catch (ArgumentException ex)
{
Console.WriteLine(ex.Message);
}
}
}
Test yourself
-
What is the difference between throw; and throw ex;?
catch (Exception ex) { throw; } // A
catch (Exception ex) { throw ex; } // B
- throw ex preserves the stack trace
- throw; cuts the stack trace
- They are the same
- throw; preserves the stack trace, throw ex cuts it
Show answer
throw; preserves the stack trace, throw ex cuts it — Correct! throw; preserves the original stack trace; throw ex cuts it.
-
Throw a new exception
if (age < 0) {
____ new ArgumentOutOfRangeException("age");
}
Show answer
if (age < 0) {
throw new ArgumentOutOfRangeException("age");
}
-
Match the expression with its description
- throw;
- Rethrow
- throw new Exception()
- New error
- throw ex;
- Cuts stack trace
Next lesson: The Exception class