What is better: int.TryParse or try { int.Parse() } catch [closed] - c#

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I know.. I know... Performance is not the main concern here, but just for curiosity, what is better?
bool parsed = int.TryParse(string, out num);
if (parsed)
...
OR
try {
int.Parse(string);
}
catch () {
do something...
}

Better is highly subjective. For instance, I personally prefer int.TryParse, since I most often don't care why the parsing fails, if it fails. However, int.Parse can (according to the documentation) throw three different exceptions:
the input is null
the input is not in a valid format
the input contains a number that produces an overflow
If you care about why it fails, then int.Parse is clearly the better choice.
As always, context is king.

Is it exceptional for the conversion to sometimes fail, or is it expected and normal that the conversion will sometimes fail? If the former, use an exception. If the latter, avoid exceptions. Exceptions are called "exceptions" for a reason; you should only use them to handle exceptional circumstances.

If it is indeed expected that the conversion will sometimes fail, I like to use int.TryParse and such neatly on one line with the conditional (Ternary) operator, like this:
int myInt = int.TryParse(myString, out myInt) ? myInt : 0;
In this case zero will be used as a default value if the TryParse method fails.
Also really useful for nullable types, which will overwrite any default value with null if the conversion fails.

The first. The second is considered coding by exception.

Personally, I'd prefer:
if (int.TryParse(string, out num))
{
...
}

The first! You should not code by exception.
you could shorten it to
if (int.TryParse(string, out num))

First, by far. As George said, second is coding by exception and has major performance impacts. And performance should be a concern, always.

Catching an Exception has more overhead, so I'll go for TryParse.
Plus, TryParse method does not throw an exception if the conversion fails. It eliminates the need to use exception handling to test for a FormatException in the event that s is invalid and cannot be successfully parsed.
That last part copy-pasted from here

Something else to keep in mind is that exceptions are logged (optionally) in the Visual Studio debug/output window. Even when the performance overhead of exceptions might be insignificant, writing a line of text for each exception when debugging can slow things right down. More noteworthy exceptions might be drowned amongst all the noise of failed integer parsing operations, too.

Related

Is it a bad idea return a tuple instead of throw an exception? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I have a method, that always has to return an object of type MyType. If it returns null it is because I don't have the needed information to return a value.
So I was thinking that a posibility it is to throw an argument exception if I don't have the needed information.
Another solution, it is to return a tuple, first item null or the object as result. The second item a string, null if I can return the value or a string with the reason why it is null.
I was consideration this second option, because I guess it is more versatile, who calls this method, if get a null, can know the reason of why it is null and don't need to handle the exception, that requieres more code. Also, if it is called in the UI layer, it can tell the user what information it is needed.
An exception it is more expensive if it is thrown, and also, from a point of view, I considerate the exception the way to handle something that I can't control in another way, but in this case I can know in advance if I have the needed information or not from the user, so it is not something unexpected like if I try to load a file and the file doesn't exist, for example, or try to connect to a network resource and the network is down.
Also, argument exception it is a generic exception, if I want to show to a user a understanding message but also I want a more detailed message for the developer, it is more complex code.
So I was wondering if really it is a bad idea to return a tuple or it is better to throw an exception.
I think a touple can be very usefull, because it can return the value of the method, but also can provide aditional information in another items.
This is a variant on the Return codes vs exception discussion.
I would recommend using a specialized type rather than just a plain tuple. This should either have a value, or a string/error code. This should force the caller to handle at least one case, for example by having OnSuccess(Action<T>) and OnFail(Action<string) methods. See Result of T for an example
If this is preferable to exceptions somewhat depend on if failure is expected or not. I think it is appropriate for something like a Parse-method. For reading a file I would prefer exceptions since reading the file can fail at any time for many possible reasons. I.e. a result object fits best with a functional style.

Try-Catch Exception abuse [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I have found some code like this:
try
{
myClass.do().ToString();
} catch () { }
which certainly results in an exception being thrown when do() returns null. You could, instead, use
(myClass.do() ?? "").ToString();
to avoid the exception being thrown. I also see code like this:
for (int i = 0; i < x.length; i++)
{
if (x.Phases[i].num == activeNum)
{
try
{
result = x.Phases[i + 1].obj;
}
catch (Exception ex) { }
}
}
I think that this is not good practice. However, I can't find any references to support my ideas.
I tried to search on web, but I did not have any luck. Most of the references or documentation was meant for C++ or Java.
Will you please help me to justify my idea with strong reference, or enlighten me if the previous approaches above are in fact acceptable.
You're correct: using exceptions for purposes of flow control is generally bad practice. It is often referred to as an anti-pattern for this reason.
You can find a detailed explanation here. While the article references Java and C++, it is also an anti-pattern in C# for much the same reasons.
For a C#/.Net specific explanation, see this MSDN article.
Your intuition is right. Exception handling is slow.
Branching (such as an underlying jump when the for-loop terminates) is very fast.
Don't waste your time on exception handling as a means of flow control.
EDIT:
Note that there is ample evidence for such claims, and that for instance, you may reference the Wikipedia article on the subject for an explicit indication that flow control is not the intended role of exception handling code in C#.

Using try catch even if no exception is expected [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
This is a public method which I don't want it to throw exception in any case.
In this example, I can't see a case where exception is thrown (am i missing something?), what is the BKM in this case? Is this a matter of preference? or there are guidelines in those cases.
public IEnumerable<DataEnumerable.Column> GetCollectionSchema(string collectionName)
{
// Is this try catch block redundant?
try
{
if (CoordinationDataCollection != null)
{
var collection = CoordinationDataCollection.FirstOrDefault(x => x.CollectionName == collectionName);
if (collection != null)
{
return collection.Schema;
}
}
}
catch(Exception ex)
{
_log.Error("Error occurred while trying to get collection schema", ex);
}
return new List<DataEnumerable.Column>();
}
It is okay for public methods to throw exceptions in exceptional cases. As long as these are documented then it should be fine.
In your example, if the CoordinationDataCollection is null then it would throw an exception.
Rather than suppressing any potential exceptions, it might be better to either document them, or allow them to be raised and allow the caller to decide what to do.
The above is just an example; a whole host of other things can go wrong.
I don't want it to throw exception in any case.
That's not possible. If the stack is nearly exhausted, it will throw a StackOverflowException which you cannot suppress.
In this example, I can't see a case where exception is thrown (am i
missing something?)
The lambda expression that is passed to FirstOrDefault will throw if the collection contains null values.
Catching and logging all exception is sometimes the right thing. You might need to suppress a warning if you use code analysis.
What you have to think about in this case for instance is what happens if your DataCollection file changes in an update and the field CollectionName changes? Or what happens if the connection to the database is unavailable.
That's what you are checking for in your try catch when you simple code such as that, you know that your code won't fall over - the catch is to catch unexpected issues aka exceptions.
First of all, public method must verify its input parameters:
Contract.Requires(!string.IsNullOrEmpty(collectionName));
The second thing: you should catch only those types of exceptions, that are prospective for your code. In other words, the method you've posted shouldn't catch Exception, because from the point of caller, it is not clear, why your method has returned an empty collection - either it is really empty, or exception happen.

Why does C# also not allow empty conditions in while loops? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Edit: I changed most of my question, because it was too long and altough my question is a request of facts, it was considered opinion based. Having said that, please read the comments where I try to explain why closing this question was wrong IMHO.
Also: I'd like to appologize for my initial question, I am not a native English speaker and I didn't know the word [blindly] had such a negative tone. I actually used the word in other questions.
Background:
Consider the following piece of C# code:
for(; /*empty condition*/ ;)
{
//Infinite loop
}
This amongst other methods is considered good practice to make an infinite loop. But when we would try a similar approach with a while loop it would never compile:
while(/*empty condition*/)
{
//Compiler error
}
At first I thought that this was some sort of bug in my compiler, but then I read the C# language specification. I found this was be design. Why? Because C# is based on C, and C behaves this way.
So now the question is, why does C behave like this? Somebody else asked this question on StackOverflow already. The answer was pretty unsatisfying and came down to this:
It behaves like this because it is described like this in the C language specification.
This answer reminded me of many discussions I had with my parents when I was a kid: "Why do I have to clean my room?" - "Because we say so.". Further answers speculate (i.e. no sources or arguments were added) that while() is "hacky" and that "using for(;;) made more sense".
My research
Edit: deleted because it was considered to long. It basically was an effort to figure out why C had this construction.
My question:
After all my research I concluded that the while loop's inability to accept empty expressions is illogical if the for loop can.
But if that is true, then why did the C# language design team copy this bevahiour?
You: "C# is based on C and why would you reinvent the wheel?"
True, but why make the same illogical decissions? If your grandfather would jump of a bridge, then would you do it too, just because you are based on him? And isn't the creation of a new language - based on an old one - the ideal situation to avoid/fix the illogical pitfalls of the old language?
So to repeat my question:
Why did the C# design team copy this behaviour?
After all my research I can only conclude that the while loop's inability to accept empty expressions is illogical.
A very far fetched conclusion. IMHO it is the for(;;) loop that is illogical (and not only in this respect).
It is clear that while() { ... } would have been possible but what exactly is the merit?
As a matter of style I would prefer for(;true;) over for(;;), it has less chance of being misread.
Being able to write a 'for-ever' loop is a minor issue, avoiding typos is much more important.
Readability is the only thing that counts, you're not making much of a case for while().
And what should happen in this statement?
if() Foo();
C11 specification states:
The statement
for ( clause-1 ; expression-2 ; expression-3 ) statement
behaves as follows: The expression expression-2 is the
controlling expression that is evaluated before each execution of the
loop body. The expression expression-3 is evaluated as a void
expression after each execution of the loop body. If clause-1 is a
declaration, the scope of any identifiers it declares is the remainder
of the declaration and the entire loop, including the other two
expressions; it is reached in the order of execution before the first
evaluation of the controlling expression. If clause-1 is an
expression, it is evaluated as a void expression before the first
evaluation of the controlling expression. 158)
Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a
nonzero constant.
which is not the case with the while-loop. However this is C11. ANSI C doesn't make this clear really. Though, I assume C# is based on how C most commonly work(s|ed), not how it's specified to work.
To speculate, I could think that the for-loop in early C wasn't well defined, so programmers found out that you can write an infinite loop like for (;;). To be compatible with old programs, the standards never forbid this. So there is really no reason to write like this. It's just history I guess.

Handling Exceptions [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am working in a code-base(C# 3.5), which is littered with exception handling blocks which return true/false, when inside in a function which returns 'bool'.
catch (Exception ex) { return false; }
This is not correct practice.I am thinking of logging the exception, and have a local variable(to function) which will be initialized.And, this variable will be returned at the end of function.
What do you think?
The usual accepted way to handle exception is to handle them only if you can do something about it. You can of course handle a generic exception just for log puroposes but you should reraise it once you're done.
Your application logic shouldn't rely on exceptions. If there is absolutely no other way to do it, then at least handle concrete exceptions instead of the generic one...
Personally, I would get rid of all of these catch blocks and let the exception bubble up when it happens.
As you say, using exceptions for application logic is bad practice.
Have a catchall exception handler that will catch all such exceptions and log them and terminate the program (if that's the right thing for this program).
It is highly subjective what you want here.
It is old C-style code to have your functions return a true/false value depending on the function succeding or not. In the C# world, it is alot more common to throw exceptions.
You can debate for a long time which is the right path to choose for your code base.
My general point of view is to stick to the exceptions, they have the advantage that they bubble up and usually require less code. And there is also great support for actually logging uncaught exceptions.
You inherited code where the original programmer just didn't want to deal with errors. As written, the program will simply malfunction (say, not save a record to the database) and there's no way to find out why it malfunctioned. Especially since this is dbase code, this will cause random data corruption and loss of precious data.
You indeed cannot leave the code the way it is. The very first thing you need to do is remove all try/catch statements so the program terminates when there's an error. Add an AppDomain.UnhandledException event handler to log the exception so you know what went wrong. Fix errors you'll encounter by correcting code or validating the data. Do expect this to take time, it is very likely that you'll discover many design problems that were shoved under a doormat before.
That's certainly better than what you've got!
Although I wouldn't recommend using the bool return value as proper exception handling, if there is already a lot of code written that way, going and making sweeping modifications everywhere may not be the best idea.
Throwing an exception is generally better than returning false - an exception can at least give the receiver some clue of what happened and why the failure occurred.
The return value of a method should be the result of a method, or it should throw an exception explaining why the requested operation could not be completed.

Categories