In this chapter, you learned how to use exception handling to deal with errors in an app. You saw exception handling in the context of a divide-by-zero example. You learned how to use try
blocks to enclose code that may throw an exception, and how to use catch
blocks to deal with exceptions that may arise. We explained the termination model of exception handling, in which, after an exception is handled, program control does not return to the throw point.
We discussed several important classes of the .NET Exception
hierarchy, including Exception
(from which user-defined exception classes are derived) and SystemException
. Next you learned how to use the finally
block to release resources whether or not an exception occurs, and how to throw and rethrow exceptions with the throw
statement. We showed how the using
statement can be used to automate the process of releasing a resource. You then saw how to obtain information about an exception using Exception
properties Message
, StackTrace
and InnerException
, and method ToString
. We demonstrated how to create your own exception classes.
We introduced C# 6’s new ?.
null-conditional operator for testing whether a reference is null
before accessing the referenced object. We also introduced nullable value types and the ??
null coalescing operator. Finally, we showed how to use C# 6’s new when
clause for adding exception filters to catch
clauses.
In the next two chapters, we present an in-depth treatment of graphical user interfaces. In these chapters and throughout the rest of the book, we use exception handling to make our examples more robust, while demonstrating new features of the language.