Home » ASP.NET Basics » 08 - Coping with Errors
8

Exception Handling

Defining exception handling

Exception refers to the situations when something unexpected happens to our application. To understand exceptions, let us consider a simple example. Imagine that we have an application that reads data from a file. The file is stored on the computer's hard disk. Everything works fine until the day when someone deletes the file, without our knowledge. Now, when the application tries to read the data, it will not find the required file. This will result in an error and may cause our application to break down. Such situations are known as Exceptions.

The .NET Framework provides a method to deal with exceptions through what is known as `exception handling'. This technique allows the developer to anticipate the situations where exceptions may occur and write code to handle them in such a way that the application can continue to work and the user is shown a friendly message that something is wrong.

In Visual C#, the structure for exception handling is as follows:

 try { write the code that can generate exception. For example, the code to open a file or connect to a database. } catch (type of exception) { write code to execute if the code in the try block generates an exception. } finally { code in this block will always execute whether an exception is generated or not. }

As we can see, the exception handling is structured in three blocks. The try block contains the code that may generate an exception. Codes for opening files, to connect to a database, and those that ivolve mathematical calculations, among others, are prime candidates for placement inside the try block because they can generate exceptions when the application is running.

The catch block contains the code that will execute if the code in the try block results in exception. We can use multiple catch blocks, one each for different types of exceptions. When an exception occurs, the catch block that matches with the type of exception will be executed.

The code in the finally block will be executed whether or not an exception is generated.