Chapter 10. Programming with Exceptions

In procedural programming, the status of a function call is often returned as an integer result code. The client code (which makes the function call) then uses this code to determine the branching of the program. Upon return of an error integer code in GUI applications, a dialog box indicating an error status is often displayed to the end user. COM programmers are familiar with the HRESULT return value, which is returned by COM components.

But using result codes has several deficiencies:

  • The client code (which makes the function call) must understand the various result codes returned by the function.

  • Depending on the specificity of the result code, the client code gets some idea of what went wrong inside the method at runtime. However, no snapshot of execution is stored for the client code to examine after the method fails.

  • There is no mechanism for tracking and logging runtime errors. Not all applications are GUI-based, and hence a runtime error cannot always be packaged as a pop-up dialog box that the user can see. Logging result codes is not very helpful. Error messages need to be logged in a manner that details the path of execution that led to the error. (Java programmers are probably thinking about the term “stack trace” here.)

Clearly, the makers of C# realized the limitations of using error codes for error management, and they devised a more rigorous mechanism of dealing with runtime execution errors through exceptions. As stated in Chapter 1, exceptions represent a breach of an implicit assumption made within code. For example, if your code tries to parse an integer from a string that contains nonnumeric characters, an exception will be thrown. However, if your code checks whether the string has only numeric digits before parsing it, then an exception will not be thrown. As one of the .NET languages, C# has built-in support for exception handling. Fortunately for Java programmers, many similarities exist between the Java try-catch-finally construct and C#'s try-catch-finally construct.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.203.172