This example catches an error and still runs the finally block.
C Sharp (C#)
try
{
int x = 5 / 0;
}
catch (DivideByZeroException e)
{
Console.WriteLine("Caught division by zero.");
}
finally
{
Console.WriteLine("Cleanup code runs.");
}
Sample Program
This program tries to divide by zero, catches the error, and then runs the finally block. The program then continues normally.
C Sharp (C#)
using System;
class Program
{
staticvoid Main()
{
try
{
Console.WriteLine("Start try block.");
int result = 10 / 0; // This causes an error
Console.WriteLine("This line will not run.");
}
catch (DivideByZeroException)
{
Console.WriteLine("Caught division by zero error.");
}
finally
{
Console.WriteLine("Finally block always runs.");
}
Console.WriteLine("Program continues.");
}
}
OutputSuccess
Important Notes
If there is a return inside try or catch, the finally block still runs before returning.
Use finally to release resources like files or connections safely.
Summary
The finally block runs no matter what happens in try or catch.
It is useful for cleanup tasks that must always happen.
You can use finally with or without catch.
Practice
(1/5)
1. What is the main purpose of the finally block in C# exception handling?
easy
A. To execute code regardless of whether an exception occurs or not
B. To catch exceptions thrown in the try block
C. To declare variables used in the try block
D. To stop the program when an exception occurs
Solution
Step 1: Understand the role of finally
The finally block runs after the try and catch blocks, no matter what happens.
Step 2: Identify its purpose
It is used to run cleanup code or important steps that must always execute, regardless of exceptions.
Final Answer:
To execute code regardless of whether an exception occurs or not -> Option A
Quick Check:
finally always runs [OK]
Hint: Remember: finally always runs, no matter what [OK]
Common Mistakes:
Confusing finally with catch block
Thinking finally only runs on exceptions
Believing finally can catch exceptions
2. Which of the following is the correct syntax for using a finally block in C#?
easy
A. try { } catch { } finally { }
B. try { } finally { } catch { }
C. try { } catch { }
D. finally { } try { } catch { }
Solution
Step 1: Recall correct order of blocks
In C#, the order is try, then catch (optional), then finally (optional).