C Sharp

Overview of Exception Handling

Exceptions are error conditions that arise when the normal flow of a code path-that is, a series of method calls on the call stack-is impractical or imprudent. It's imperative to understand the difference here between an exception and an expected event (such as reaching the end of a file). If you have a method that is sequentially reading through a file, you know that at some point it's going to reach the end of the file. Therefore, this event is hardly exceptional in nature and certainly doesn't prevent the application from continuing. However, if you're attempting to read through a file and the operating system alerts you to the fact that a disk error has been detected, this is certainly an exceptional situation and definitely one that will affect the normal flow of your method's attempt to continue reading the file.

Most exceptions also involve another problem: context. Let's look at an example. Assuming that you're writing tightly cohesive code-code in which one method is responsible for one action-your (pseudo)code might look like this: -

public void Foo()
    File file = OpenFile(String fileName);
    while (!file.IsEOF())
        String record = file.ReadRecord();
public void OpenFile(String fileName)
    // Attempt to lock and open file.

Note that if the OpenFile method fails, it cannot handle the error. This is because its only responsibility is to open files. It can't determine whether the inability to open the specified file constitutes a catastrophic error or a minor annoyance. Therefore, OpenFile can't handle the error condition because the method is said to not be in the correct context.

This is the entire reason for the existence of exception handling: one method determines that an exception condition has been reached and happens not to be in the correct context to deal with the error. It signals to the runtime that an error has occurred. The runtime traverses back up the call stack until it finds a method that can properly deal with the error condition. Obviously, this becomes even more important if the code path is five methods deep with the fifth method reaching an error condition and the first method being the only method that can deal with the error correctly. Now let's look at the syntax used in exception handling.

by BrainBellupdated