The try and catch Statements
As you saw, the exception in your previous example stopped your program dead. That’s usually not the desired behavior. What you need is a way to tell the compiler, “If any exceptions are thrown in this section of code, take this action.” That way, your program can continue on from the error or at least end gracefully. This process is called handling the exception. To handle exceptions, take the following steps:
Execute any code that you suspect might throw an exception (such as code that opens a file or allocates memory) within a
tryblock.Catch any exceptions that are thrown in a
catchblock.
A try block is created using the keyword try and is enclosed in braces. You don’t need any extra code to create the try block; it just indicates the area of code where you want to watch for exceptions. A catch block holds the code where you take action based on the type of exception thrown. It is created using the keyword catch and is also enclosed in braces. In the abstract, the try/catch block looks like this:
try
{
// Potentially hazardous code goes here.
}
catch
{
// Exception handler code goes here.
}Example 16-2 illustrates these constructs. Note that Example 16-2 is identical to Example 16-1 except that now the program includes a try/catch block.
Example 16-2. The try and catch blocks in this example let you avoid the crash of the previous example
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Example_16_2_ _ _ ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access