C# Exceptions
(Page 1 of 4 )
In this fourth part of a ten-part series on C#, you will learn about common exceptions and more. It is excerpted from chapter four of
C# 3.0 in a Nutshell, Third Edition, A Desktop Quick Reference, written by Joseph Albahari and Ben Albahari (O'Reilly; ISBN: 0596527578). Copyright © 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.
The catch Clause
A catch clause specifies what type of exception to catch. This must either be System.Exception or a subclass of System.Exception.
CatchingSystem.Exceptioncatches all possible errors. This is useful when:
- Your program can potentially recover regardless of the specific exception type.
- You plan to rethrow the exception (perhaps after logging it).
- Your error handler is the last resort, prior to termination of the program.
More typically, though, you catch specific exception types, in order to avoid having to deal with circumstances for which your handler wasn’t designed (e.g., anOutOfMemoryException).
You can handle multiple exception types with multiplecatchclauses:
class Test
{
static void Main (string[] args)
{
try
{
byte b = byte.Parse (args[0]);
Console.WriteLine (b);
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine ("Please provide at least one argument");
}
catch (FormatException ex)
{
Console.WriteLine ("That's not a number!");
}
catch (OverflowException ex)
{
Console.WriteLine ("You've given me more than a byte!");
}
}
}
Only onecatchclause executes for a given exception. If you want to include a safety net to catch more general exceptions (such asSystem.Exception), you must put the more specific handlers first.
An exception can be caught without specifying a variable, if you don’t need to access its properties:
catch (StackOverflowException) // no variable
{
...
}
Furthermore, you can omit both the variable and the type (meaning that all exceptions will be caught):
catch { ... }
In languages other than C#, it is possible (though not recommended) to throw an object that does not derive fromException. The CLR automatically wraps that object in aRuntimeWrapped-Exceptionclass (which does derive fromException).
Next: The finally Block >>
More C# Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of C# 3.0 in a Nutshell, Third Edition, A Desktop Quick Reference, written by Joseph Albahari and Ben Albahari (O'Reilly; ISBN: 0596527578). Check it out today at your favorite bookstore. Buy this book now.
|
|