Exception Objects
So
far you’ve been using the exception as a
sentinel—that is, the presence of the exception
signals the error—but you haven’t
touched or examined the Exception
object itself.
The System.Exception
object provides a number of
useful methods and properties. The Message
property provides information about the exception, such as why it was
thrown. The Message
property is read-only; the
code throwing the exception can set the Message
property as an argument to the exception constructor.
The HelpLink
property provides a link to the help
file associated with the exception. This property is read/write.
Tip
VB6
programmers
take
note: In C#, you need to be careful when
declaring and instantiating object variables on the same line of
code. If there is a possibility that an error could be thrown in the
constructor method, then you might be temped to put the variable
declaration and instantiation inside the try
block. But if you do that, the variable will only be scoped within
the try
block and it can’t be
referenced within the catch
or
finally
blocks. The best approach is to
declare the object variable
before the try
block and
instantiate it within the
try
block.
The StackTrace
property is read-only and is set by
the runtime. In Example 11-6, the
Exception.HelpLink
property is set and retrieved
to provide information to the user about the
DivideByZeroException
. The
StackTrace
property of the exception is used to provide a stack trace for the error statement. A stack trace ...
Get Programming C#, Third Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.