Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is "Try" supposed to be used in C# method names?

We were discussing with our coworkers on what it means if the method name starts with "Try".

There were the following opinions:

  • Use "Try" when the method can return a null value.
  • Use "Try" when the method will not throw an exception.

What is the official definition? What does "Try" say in the method name? Is there some official guideline about this?

like image 411
ms007 Avatar asked Jun 20 '13 07:06

ms007


People also ask

When should you use try?

The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

What is try in C?

The try-except statement is a Microsoft extension to the C language that enables applications to gain control of a program when events that normally terminate execution occur. Such events are called exceptions, and the mechanism that deals with exceptions is called structured exception handling.

What is the use of try and catch in C?

It uses a long jump out of the current function to the try block. The try block then uses an if/else to skip the code block to the catch block which check the local variable to see if it should catch. This uses a global pointer so the longjmp() knows what try was last run.

Does try catch slow down code C++?

Typically yes, but unless it's a time-critical, called-a-million-times, must-be-really-fast portion of code, I wouldn't base my decision of whether or not to use exceptions on this.


1 Answers

This is known as the TryParse pattern and has been documented by Microsoft. The official Exceptions and Performance MSDN page says:

Consider the TryParse pattern for members that may throw exceptions in common scenarios to avoid performance problems related to exceptions.

Thus if you have code for which a regular use case would mean that it might throw an exception (such as parsing an int), the TryParse pattern makes sense.

like image 178
Erik Schierboom Avatar answered Sep 28 '22 20:09

Erik Schierboom