O'Reilly logo

Learning C# 2005, 2nd Edition by Brian MacDonald, Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 16: Throwing and Catching Exceptions

Quiz

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.

Exercises

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; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required