You are on page 1of 13

CPSC 122 – Data Structures

Exceptions
What is an Exception

š A signal that a problem has occurred during program execution that requires special
processing

š Exceptions should only occur during “exceptional” circumstances

š C++ provides a mechanism for handling exceptions so that programs don’t just “crash” or
stop executing, without a chance to recover
Error Testing

š Signal errors or unexpected events that occur while a program is running.

š Error testing is usually involves if statements or other control mechanisms


What is Exception Handling

š A process for detecting and resolving exceptions

š C++ exception handling is built on three keywords


§ try
§ catch
§ throw
Exceptions handle complex error conditions

š error occurs -- an exception is “thrown”


š Same problem different code

throw key word is followed by an argument, which can be any value


Handling an Exception
try Block

š Contains code that might generate an exception


catch Handler

š Executes as a result of an exception

š The correct handler is “activated” when a match occurs between the type of exception
thrown and type of parameter for the handler

š An exception parameter should always be declared as a reference to the type of


exception in the handler
Division function Example

If this statement throws an exception...

... then this statement is


skipped.
Division function Example
Multiple catch blocks

You might also like