C sharp - try, catch, and finally in C#
<p>C# provides the <code>try</code>, <code>catch</code>, and <code>finally</code> blocks to handle <strong>exceptions</strong> — unexpected errors that occur during program execution (like dividing by zero, file not found, etc.).</p>
<h2>1. <code>try</code> Block</h2>
<ul>
<li>
<p>The <code>try</code> block contains the code that <strong>might throw an exception</strong>.</p>
</li>
<li>
<p>If an exception occurs, the flow jumps to the <code>catch</code> block.</p>
</li>
</ul>
<pre><code class="language-csharp">try
{
int x = 10;
int y = 0;
int result = x / y; // This will throw DivideByZeroException
}
</code></pre>
<h2> 2. <code>catch</code> Block</h2>
<ul>
<li>
<p>The <code>catch</code> block <strong>handles the exception</strong>.</p>
</li>
<li>
<p>You can catch specific exception types (recommended) or use a general one.</p>
</li>
</ul>
<h2>3. <code>finally</code> Block (Optional)</h2>
<ul>
<li>
<p>The <code>finally</code> block <strong>always executes</strong>, regardless of whether an exception was thrown or not.</p>
</li>
<li>
<p>It's typically used to <strong>release resources</strong> (e.g., closing files, database connections).</p>
</li>
</ul>
<ul>
<li>
<p>To <strong>prevent program crashes</strong>.</p>
</li>
<li>
<p>To handle <strong>errors gracefully</strong> (show user-friendly messages).</p>
</li>
<li>
<p>To ensure <strong>resources are cleaned up properly</strong>.</p>
</li>
</ul>
<h2>Example Putting It All Together</h2>
<pre><code class="language-csharp">using System;
class Program
{
static void Main()
{
try
{
int a = 10, b = 0;
int result = a / b;
Console.WriteLine("Result: " + result);
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero!");
}
finally
{
Console.WriteLine("Finished error handling.");
}
}
}
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>Cannot divide by zero!
Finished error handling.
</code></pre>
<p> </p>