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(); } CloseFile(); } 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.