Reputation: 17786
I need some help on how to use try/catch
correctly. In the following example I am using the Google Tasks API, but that's not the important thing.
So here's my current code:
try
{
// try something that could cause an exception
Task result = service.Tasks.Patch(body, listId, taskId).Execute();
}
catch (Google.GoogleApiException ex)
{
// handle exception
Debug.WriteLine("exception");
}
This code tries to do something and I am catching possible exceptions. Now instead of only outputting a message when an error occurs (in the catch
block) I also want to output a message when everything is ok. I am not sure though, where to put such a message?
finally
block, it's always displayed, even if there are errorstry/catch
and maybe finally
, it's always displayed, even if there are errorsSo, would I put a success message in the try
block like this?
try
{
// try something that could cause an exception
Task result = service.Tasks.Patch(body, listId, taskId).Execute();
Debug.WriteLine("task updated successfully"); // <------------------ success message
}
catch (Google.GoogleApiException ex)
{
// handle exception
Debug.WriteLine("exception");
}
My understanding was that try
contains only code that can fail and obviously Debug.WriteLine("task updated successfully");
is nothing that can fail, but still included in the try block. Please let me know if my understanding of a try
block containing only code that can fail was wrong and if it's normal to include a success message in the try
block or what is the best practice for my use case.
Upvotes: 0
Views: 169
Reputation: 68
No, you don't have to only include code that can fail in the try block. You should also include code that requires that call to succeed. For example, if you need to connect to a database and run some queries you would do it all in the try block.
You might want to include a second catch block to catch other exceptions. Just a random thought.
Upvotes: 1