Menu
Coddy logo textTech

Try-Catch Basics

Part of the Logic & Flow section of Coddy's C# journey — lesson 23 of 66.

Exception handling in C# allows you to manage runtime errors gracefully. The try-catch block is the fundamental way to handle exceptions.

Create a basic try-catch block:

try
{
    // Code that might throw an exception (error)
    int result = 10 / 0; // This will throw a DivideByZeroException
}
catch (Exception ex)
{
    // Handle the exception
    Console.WriteLine("An error occurred: " + ex.Message);
}

After executing the above code, instead of your program crashing, you'll see:

An error occurred: Attempted to divide by zero.

You can continue executing code after the catch block:

try
{
    int result = 10 / 0;
    Console.WriteLine("This won't execute");
}
catch (Exception ex)
{
    Console.WriteLine("Caught an error: " + ex.Message);
}

Console.WriteLine("Program continues running");
challenge icon

Challenge

Easy

Create a method named DivideNumbers that takes two integers as parameters:

  • numerator - The number to be divided
  • denominator - The number to divide by

The method should:

  1. Try to divide the numerator by the denominator
  2. Return the result if successful
  3. Catch any DivideByZeroException and print exactly: "Cannot divide by zero!"
  4. Return 0 if an exception occurs

Cheat sheet

Exception handling in C# uses try-catch blocks to manage runtime errors gracefully:

try
{
    // Code that might throw an exception
    int result = 10 / 0;
}
catch (Exception ex)
{
    // Handle the exception
    Console.WriteLine("An error occurred: " + ex.Message);
}

Code execution continues after the catch block, preventing the program from crashing. You can catch specific exception types like DivideByZeroException for more targeted error handling.

Try it yourself

using System;

class Program {
    public static int DivideNumbers(int numerator, int denominator) {
        // Write your code here
    }
    
    static void Main(string[] args) {
        int numerator = int.Parse(Console.ReadLine());
        int denominator = int.Parse(Console.ReadLine());
        
        int result = DivideNumbers(numerator, denominator);
        Console.WriteLine(result);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow