Exception Handling: Try And Catch

Lesson 4.3: Exception Handling with Try-Catch Blocks


In previous lessons, you learned about runtime errors (exceptions) and how they can cause your program to crash. In this lesson, you'll discover how to gracefully handle exceptions using try-catch blocks, preventing unexpected crashes and improving the robustness of your code.


What is Exception Handling?


Exception handling is the process of anticipating, detecting, and resolving runtime errors in your program.

The goal is to prevent your program from abruptly stopping due to an error and instead provide a way to recover or inform the user.

Try-Catch Blocks: The Basics


A try-catch block is a structured way to handle exceptions in C#.

The try block contains the code that you suspect might throw an exception.

The catch block(s) follow the try block and specify how to handle different types of exceptions if they occur.

C#

try

{

    // Code that might throw an exception

    int result = 10 / 0; // This will throw a DivideByZeroException

}

catch (DivideByZeroException ex) // Specific exception handling

{

    Console.WriteLine("Error: Division by zero is not allowed.");

}

catch (Exception ex) // General exception handling

{

    Console.WriteLine("An unexpected error occurred: " + ex.Message);

}

How It Works


The code within the try block is executed.

If an exception occurs, the execution jumps to the first catch block that matches the exception type.

The code inside the matching catch block is executed, allowing you to handle the error gracefully.

If no matching catch block is found, the program terminates with an unhandled exception error.

Multiple Catch Blocks


You can have multiple catch blocks to handle different types of exceptions individually.

It's a good practice to catch specific exceptions first and then have a general catch block to handle any unexpected exceptions.

The finally Block (Optional)


You can add a finally block after the catch blocks.

Code in the finally block is always executed, regardless of whether an exception occurred or not.

It's often used for cleanup tasks like closing files or releasing resources.

C#

try

{

    // ... (Code that might throw an exception)

}

catch (Exception ex)

{

    // ... (Handle the exception)

}

finally 

{

    // ... (Cleanup code)

}

Best Practices


Don't Overuse Exceptions: Exceptions should be used for exceptional circumstances, not for normal program flow.

Be Specific: Catch specific exception types when possible to provide more targeted error handling.

Log Errors: Consider logging details about exceptions to help diagnose and troubleshoot problems later.

Don't Swallow Exceptions: Avoid empty catch blocks. At the very least, log the error message.

Example: Handling a FileNotFoundException


C#

try

{

    string text = File.ReadAllText("nonexistent_file.txt"); // This file doesn't exist

}

catch (FileNotFoundException ex)

{

    Console.WriteLine("File not found: " + ex.FileName);

}

By understanding and using exception handling, you'll be able to write more robust and user-friendly C# programs.

Course Syllabus