Errors happen, and they are not always caused by the”person who coded the application. Sometimes your application will generate an error because of an action that was initiated by the end user of your application or it might be simply due to the environmental context in which your code is running. In any case, you should anticipate errors occurring in your applications and code accordingly.
The .NET Framework has enhanced the ways in which you deal with errors. ‘C#’s mechanism for handling error conditions allows you to provide custom handling for each type of error condition as well as to separate code that identifies errors from the code that handles them.
The main topics covered in this chapter include:
- Looking at the exception classes
- Using try – catch – finally to capture exceptions
- Creating user-defined exceptions.
By the end of the chapter, you will have a good grasp on advanced exception handling in your C# applications.
No matter how good your coding is, your programs should have the ability to handle any possible errors that may occur. For example, in the middle of some complex processing your code may discover that it doesn’t have permission to read a file, or, while it is sending network requests, the network may go down. In such exceptional situations, it is not enough for a method to simply return an appropriate error code – there might be 15 or 20 nested method calls, so what you really want the program to do is jump back up through all those 15 or 20 calls in order to exit the task completely and take the appropriate counteractions. The C# language has very good facilities to handle this kind of situation, through the mechanism known as exception handling.
Error-handling faciIities in Visual Basic 6 are very restricted and essentially limited to the On Error GoTo statement. If you are coming from a Visual Basic 6 background, you will find that C# exceptions open a completely new world of error handling in your programs. Java and C++.developers, however, will be familiar with the principle of exceptions because these languages handle errors in a similar way to Ct. Developers using C++ are sometimes wary of exceptions because of possible C++ performance implications, but this is not the case in Ct. Using exceptions in C# rode in general does not adversely addict performance. Visual Basic developers will find that working with exceptions in C# is very similar to using exceptions in VisuaIBasic (except for the syntax differences) .