Rogue Wave banner
Previous fileTop of DocumentContentsIndex pageNext file
Essential Tools Module User's Guide
Rogue Wave web site:  Home Page  |  Main Documentation Page

11.4 Example

This section provides a series of examples to illustrate how the use of a scope guard can aid in error handling.

Let's consider this simple example that opens a file and inserts it into a cache.

The above code has no error handling and is not safe. It does not consider control flow or what happens after the file is opened. If an exception is thrown or the function exits early, nothing ensures that the file is closed or that the mutex is released. We can fix this by reorganizing the code or adding a few try/catch blocks to handle exceptions.

That's an improvement -- except the code is now less efficient and more complicated. And this is a simple application; the more complex the flow, or special cases we have to handle, the more complicated the code will become.

To make this code safe is trivial, and the additional overhead is small.

//1

Creates a guard that ensures the file f is closed on exit from scope.

//2

Creates another guard to ensure that mutex is released on exit from scope.

//3

Inserts the file into the cache. At this point, there is no need to explicitly close the file f because the guard will call the function to close it.

//4

Dismisses the file guard. Since the file has by this time been successfully inserted into the cache, we do not want the file to be closed when we leave this scope.

Now our code safely, cleanly and efficiently ensures that all resources are cleaned up.



Previous fileTop of DocumentContentsNo linkNext file

Copyright © Rogue Wave Software, Inc. All Rights Reserved.

The Rogue Wave name and logo, and SourcePro, are registered trademarks of Rogue Wave Software. All other trademarks are the property of their respective owners.
Provide feedback to Rogue Wave about its documentation.