Try Catch Finally - potatoscript/csharp GitHub Wiki
β‘ Try-Catch-Finally in C# β‘
π₯ What is Try-Catch-Finally? π₯
In C#, when we write code, sometimes things go wrong! π₯ Imagine youβre trying to open a cookie jar, but oh no! The lid is stuck! π± You try again and again, but it wonβt open. Finally, you get help and solve the problem. πͺ
In programming, this is where Try-Catch-Finally comes in.
try
β You try to do something (like open the cookie jar).catch
β If something goes wrong, you catch the error and handle it.finally
β No matter what happens, this part always runs at the end.
π― Why Do We Need Try-Catch-Finally?
- Prevents crashes β Stops the program from breaking when errors occur.
- Handles errors gracefully β Gives you control over what to do when something goes wrong.
- Ensures cleanup β The
finally
block helps clean up resources, like closing a file or database connection.
π Basic Structure of Try-Catch-Finally
Hereβs how it looks:
try
{
// Try to do something risky
}
catch (Exception e)
{
// Handle the error here
}
finally
{
// This code always runs, no matter what happens
}
π Example: Try-Catch-Finally with Explanation
π Story Time: Max and the Cookie Jar
Max loves cookies, and he tries to open the cookie jar. But sometimes, the jar gets stuck! π₯΄
Letβs see how we can write this in C#:
using System;
class Program
{
static void Main()
{
try
{
// Max tries to open the cookie jar
Console.WriteLine("Max is trying to open the cookie jar...");
// Oh no! An error happens (simulate an error)
throw new Exception("The lid is stuck!");
}
catch (Exception e)
{
// Max handles the error
Console.WriteLine("Oops! Something went wrong: " + e.Message);
}
finally
{
// Max cleans up (like putting the jar back)
Console.WriteLine("Max puts the cookie jar back safely.");
}
}
}
π§ Explanation:
-
try
Block:- Max tries to open the cookie jar.
- But something goes wrong (
throw new Exception
), and an error occurs.
-
catch
Block:- Max catches the error and shows the message:
π£οΈ βOops! Something went wrong: The lid is stuck!β
- Max catches the error and shows the message:
-
finally
Block:- No matter what happens, Max always puts the jar back at the end.
π¨ What Happens When No Error Occurs?
If no error happens, the catch
block is skipped but the finally
block still runs.
π₯ Example: No Error in the Cookie Jar
using System;
class Program
{
static void Main()
{
try
{
// No error this time
Console.WriteLine("Max opens the cookie jar successfully!");
}
catch (Exception e)
{
Console.WriteLine("Oops! Something went wrong: " + e.Message);
}
finally
{
Console.WriteLine("Max puts the cookie jar back safely.");
}
}
}
π Output:
Max opens the cookie jar successfully!
Max puts the cookie jar back safely.
π₯ Multiple Catch Blocks: Catching Different Errors
Sometimes, different errors can happen, and we might need to handle them differently.
π₯ Example: Handling Multiple Errors
using System;
class Program
{
static void Main()
{
try
{
Console.WriteLine("Enter a number:");
int number = int.Parse(Console.ReadLine()); // Try to convert user input
}
catch (FormatException)
{
// Handles format errors (e.g., user types letters instead of numbers)
Console.WriteLine("Oops! Please enter a valid number.");
}
catch (OverflowException)
{
// Handles very large numbers
Console.WriteLine("The number is too big!");
}
catch (Exception e)
{
// Handles any other unexpected errors
Console.WriteLine("Something went wrong: " + e.Message);
}
finally
{
Console.WriteLine("Program finished.");
}
}
}
π Possible Outputs:
Enter a number:
abc
Oops! Please enter a valid number.
Program finished.
Enter a number:
999999999999999999
The number is too big!
Program finished.
finally
to Clean Up Resources
π§Ή Using The finally
block is great when you need to release resources (like closing a file or database connection).
π₯ Example: Closing a File Properly
using System;
using System.IO;
class Program
{
static void Main()
{
StreamReader file = null;
try
{
// Try to open and read the file
file = new StreamReader("potato.txt");
string content = file.ReadToEnd();
Console.WriteLine(content);
}
catch (FileNotFoundException)
{
Console.WriteLine("File not found! Please check the file name.");
}
finally
{
// Close the file to release resources
if (file != null)
{
file.Close();
Console.WriteLine("File is closed.");
}
}
}
}
π₯ Advanced: Throwing Custom Exceptions
Sometimes, we want to create our own errors when something specific goes wrong. You can use throw
to raise an error.
π₯ Example: Throwing Custom Error
using System;
class Program
{
static void Main()
{
try
{
int cookies = 0;
if (cookies == 0)
{
// Throw custom error if no cookies are left
throw new Exception("No cookies left! πͺ");
}
}
catch (Exception e)
{
Console.WriteLine("Oops! " + e.Message);
}
finally
{
Console.WriteLine("Max cleans up the kitchen.");
}
}
}
π Output:
Oops! No cookies left! πͺ
Max cleans up the kitchen.