You are allowed to create and throw exceptions in your own code. Instantiating an exception is done the same way that any other C# object.
Exception ex = new Exception();
// constructor with an overload that takes a message string
Exception ex = new Exception("Error message");
You can then use the throw
keyword to raise the exception:
try
{
throw new Exception("Error");
}
catch (Exception ex)
{
Console.Write(ex.Message); // Logs 'Error' to the output window
}
Note: If you're throwing a new exception inside a catch block, ensure that the original exception is passed as "inner exception", e.g.
void DoSomething()
{
int b=1; int c=5;
try
{
var a = 1;
b = a - 1;
c = a / b;
a = a / c;
}
catch (DivideByZeroException dEx) when (b==0)
{
// we're throwing the same kind of exception
throw new DivideByZeroException("Cannot divide by b because it is zero", dEx);
}
catch (DivideByZeroException dEx) when (c==0)
{
// we're throwing the same kind of exception
throw new DivideByZeroException("Cannot divide by c because it is zero", dEx);
}
}
void Main()
{
try
{
DoSomething();
}
catch (Exception ex)
{
// Logs full error information (incl. inner exception)
Console.Write(ex.ToString());
}
}
In this case it is assumed that the exception cannot be handled but some useful information is added to the message (and the original exception can still be accessed via ex.InnerException
by an outer exception block).
It will show something like:
System.DivideByZeroException: Cannot divide by b because it is zero ---> System.DivideByZeroException: Attempted to divide by zero.
at UserQuery.g__DoSomething0_0() in C:[...]\LINQPadQuery.cs:line 36
--- End of inner exception stack trace ---
at UserQuery.g__DoSomething0_0() in C:[...]\LINQPadQuery.cs:line 42
at UserQuery.Main() in C:[...]\LINQPadQuery.cs:line 55
If you're trying this example in LinqPad, you'll notice that the line numbers aren't very meaningful (they don't always help you). But passing a helpful error text as suggested above oftentimes significantly reduces the time to track down the location of the error, which is in this example clearly the line
c = a / b;
in function DoSomething()
.