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
EasyCreate a method named DivideNumbers that takes two integers as parameters:
numerator- The number to be divideddenominator- The number to divide by
The method should:
- Try to divide the numerator by the denominator
- Return the result if successful
- Catch any DivideByZeroException and print exactly: "Cannot divide by zero!"
- 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);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety