Hi @Shervan360 , Welcome to Microsoft Q&A,
First read the documentation on the official website: Exception and try-catch
Before using try catch, you need to understand what your purpose is?
Without a try-catch block, the program may crash when an unhandled exception occurs. Using try-catch, you can catch exceptions and take appropriate action, such as logging the error, providing a friendly error message to the user, or reverting to a known safe state.
You can first use Exception to get the type of possible errors, and then handle them in detail.
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
Sometimes some errors may not be urgent to handle at the moment, and you can use catch to record them on the stack. Add finally// code that will be executed regardless of whether an exception occurs or not
It is generally not advisable to use large blocks of code in try.
Regarding TRY-catch you can also check out these: Why is try {...} finally {...} good; try {...} catch{} bad? Why catch and rethrow an exception in C#? How using try catch for exception handling is best practice
Regarding using with using, everyone has different habits: try/catch + using, right syntax
In my daily usage I usually use when creating a resource, make sure it is released
using (var resource = new SomeDisposableResource())
{
try
{
//Code to use resources
}
catch (Exception ex)
{
// Handle possible exceptions
Console.WriteLine($"Exception occurred: {ex.Message}");
}
} // Here, use the using statement to ensure that the resource is released, and the resource cleanup operation will be performed even if an exception occurs.
Hope it can give you some help.
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.