Chapter 16: Throwing and Catching Exceptions


Solution to Question 16–1.

An exception is an object (derived from System.Exception) that contains information about a problematic event. The framework supports throwing exceptions to stop processing and catching events to handle the problem and resume processing.

Solution to Question 16–2.

The stack is unwound until a handler is found, or else the exception is handled by the CLR, which terminates the program.

Solution to Question 16–3.

You create a try/catch block; the catch part is the exception handler.

Solution to Question 16–4.

The syntax is:

throw new Sytem.Arg'umentNullException(  )
Solution to Question 16–5.

You can write multiple exception handlers to handle different exceptions; the first handler that catches the thrown exception will prevent further handling. Beware of inheritance complications in the ordering of your handlers.

Solution to Question 16–6.

If you have code that must run whether or not an exception is thrown (to close a file, for example), place that code in the finally block. You must have a try for the finally, but a catch is optional.


Solution to Exercise 16-1.

Create a Cat class with one int property: Age. Write a program that creates a List of Cat objects in a try block. Create multiple catch statements to handle an ArgumentOutOfRangeException, and an unknown exception, and a finally block to simulate deallocating the Cat objects. Write test code to throw an exception that you will catch and handle.

using System; ...

Get Learning C# 2005, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.