Try...Catch...Finally
Explore how to manage exceptions in C# using try, catch, and finally blocks. Understand how to prevent crashes by handling errors like out-of-range array access, and learn to use finally blocks for essential cleanup actions, ensuring your applications run reliably and release resources properly.
We'll cover the following...
Program errors are unavoidable. They can happen because our application is trying to reach a server that is not responding, because we run out of computer memory, or because our program is trying to read a non-existent file. In any case, it is likely that an exception occurs.
Exceptions are program states where the application can no longer continue to run normally, so we have to address them.
Consider the following example. We create an array of size four, but we attempt to access the fifth element (which does not exist). This produces an exception.
Line 2: We initialize an integer array named
numberswith four elements.Line 6: We attempt to print the element at index
4. Since arrays are zero-indexed, the valid indices are 0 through 3. This line triggers a runtime error.
The result of execution is an unhandled exception of type IndexOutOfRangeException. This exception halts execution because the code tried to access an array index outside of its allocated bounds.