1. Computing & Technology

Discuss in my forum

Structured Error Handling

By , About.com Guide

9 of 9

Are Exceptions "The Way to Go" ?

Checking for exceptions using a Try-Catch structure isn't the only way to handle errors. It's usually a faster and often better design to use "defensive programming" (also called "validation") by checking for problems before they happen. For example, an earlier example intercepted an error condition when a file didn't exist. You could write code that uses the handy FileExists method in VB.NET:

~~~~~~~~~~~~~~~~~~~~~~~~~
If File.Exists("D:George.txt") Then
  ' Process the file
Else
  ' Notify the user that the file doesn't exist
End If
~~~~~~~~~~~~~~~~~~~~~~~~~

To decide which one to use, think about how often the error occurs. If the error is relatively rare, then a Try-Catch block is probably more efficient since no code is executed until the actual error is thrown. But if the error is frequent, use defensive programming. In most cases, you'll use a combination of the two, especially since it's often not possible to anticipate errors and a well-crafted Try-Catch structure can prevent problems that you don't even know about yet.

©2012 About.com. All rights reserved.

A part of The New York Times Company.