Try-Catch Exception abuse [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 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#.

Related

Best practice exception handling [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
Comming from here, I'm not sure about exception handling. MSDN shows the frist way. Is the second one also ok? It's shorter and should produce the same output.
Question: Can I use the second way without any side effects?
try
{
string s = null;
ProcessString(s);
}
catch (ArgumentNullException e)
{
LogError(e.Message);
}
catch (Exception e)
{
LogError("Error");
}
or
try
{
string s = null;
ProcessString(s);
}
catch (Exception e)
{
LogError((e is ArgumentNullException) ? e.Message : "Error");
}
First of all, logging "Error" string when you have unknown exception is very bad practice. You should log error details - message, inner exception(s) etc. That's why logging frameworks provide methods which accept Exception object which would be logged.
Next, you should catch separate types of exception only if you handle them differently. In your case there is simple error logging in both cases, so you don't need to distinguish ArgumentNullException from other exceptions:
try
{
ProcessString(null);
}
catch (Exception e)
{
LogError("Failed to process string", e);
}
And last - don't write your own logging framework - take a look on NLog, log4net etc.
Also note that usually you should handle only high-level exceptions. E.g. if you have ArgumentNullException or IndexOutOfRangeException when you are trying to do some business operation, it's not good to show these low-level exceptions to user. You usually wrap them in custom high-level exception (e.g. DataMigrationException) and handle them later
The answer really is "it depends".
It's not that bad, but more specific exceptions are better. When you're more specific, it means that you actually understand, more concretely, what your application is trying to do as well as have more control over it. You should really just handle the exceptions you expect, and treat everything else as a bug.
If you're specifically catching the exceptions that you know a code block or method can throw, then there's a higher likelihood you can actually recover instead of just logging and hoping for the best.

When to create a new function? [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 had an argument with my teammate about the following.
We need to parse a symbol in a string to int(it is always a digit), this particular functionality is used in a number of places. So this can be done this way:
var a = int.Parse(str[i].ToString());
The argument was: do we need to create a function for this.
int ToInt(char c) {
return int.Parse(c.ToString());
}
that can be used:
var a = ToInt(str[i]);
My opinion is that creating such a function is bad: it gives no benefits except for typing couple characters less (no, as we have autocomplete), but such practice increase a codebase and makes code more complecated to read by introducing additional functions. My teammate's reason is that this is more convinient to call just one such function and there is nothing bad in such a practice.
Actually question relates to a general: when it is ok(if at all) to wrapp combination of 2-3-4 functions with a new function?
So I would like to hear your opinions on that.
I argee that this is mostly defined based on personal preferences. But also I would like to hear some objective factors to define a convention for such situations in our project.
There are many reasons to create a new sub-routine/method/function. Here is a list of just a few.
When the subroutine is called more than once.
If it makes your code easier to read/understand.
Personal preference.
Actually, the design can be done in many ways of course, and depends on the actual design of the whole software, readability, easy of refactoring, and encapsulation. These things are to be considered on each occasion by its own.
But on this specific case, I think its better to keep it without a function and use it as the first example for many reasons:
Its actually one line of code.
The overhead of calling a function in performance will be far more the benefit you get from making it.
The compiler itself probably will unwrap it again into the one line call if you make it a function, though its not always the case.
The benefit you get from doing so, will be mainly if you want to add error checking, TryParse, etc... in the function.

Should I throw a KeyNotFoundException for a database lookup? [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 5 years ago.
Improve this question
I've got some code that, given an ID, returns an item from the database. If no item matches the given ID, is it appropriate to throw a KeyNotFoundException, or are such exceptions meant only for Dictionary types?
Depending on the framework you're using to access the database (ODBC, ADO.NET, etc.) there's likely a better alternative that the framework would throw.
The System.Data namespace contains several such exceptions as examples: http://msdn.microsoft.com/library/system.data.
Really, though, as long as you document what exception you're throwing and in what conditions it doesn't matter too much. Using something common is best because people may assume, but if they are reading documentation they will handle whatever exception you say would be thrown.
The MSDN page for KeyNotFoundException states:
The exception that is thrown when the key specified for accessing an element in a collection does not match any key in the collection.
Semantically a KeyNotFoundException would be appropriate. Just make sure your error message is descriptive enough to actually help when debugging. Also, remember that you lose any contextual type information that using a custom exception type would give you.
A custom exception type gives you the ability to differentiate between the two conditions using general C# idioms, like so:
try
{
// do some database stuff
}
catch(KeyNotFoundException e)
{
// Here you know that it was more than likely caused by a Dictionary
// or some such collection
}
catch(DatabaseKeyNotFoundException e)
{
// Here you know that it was caused by a DB record not being found
}
Whichever you choose, just make sure you think about it, that it's consistent and logical. Don't just choose one because it's easier.
MSDN says yes* (if you consider a database table a collection) -
The exception that is thrown when the key specified for accessing an element in a collection does not match any key in the collection.
Why not just return false or some other indication that the value was not in the database?

is having fewer lines of code always better? [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
Which is best?
private long sumVals()
{
return (dbReturn("NUns") / dbReturn("TSpd")) * 60;
}
private long dbReturn(string dbField)
{
// ... access db, get value
return retVal;
}
or
private long sumVals()
{
long numUnits = dbReturn("NUns");
long targetSpeed = dbReturn("TSpd");
return (numUnits / targetSpeed) * 60;
}
private long dbReturn(string dbField)
{
// ... access db, get value
return retVal;
}
Is it better to try and put it all onto one line, so there is less code overall, or to spread it out like in the second one?
Is one or the other quicker? Is there a benefit, eg, while compiling?
Your case is simple, so the first one is OK. But in general, I would go for the second one.
It is important that you (and others) can read the code, but you don't need to save memory (fewer lines of code as well as fewer variables).
Your code will be easier to understand and debug if you choose to write it the second way. You also don't have to have a lot of comments if your variable names explain the code well enough, which makes your code easier to read in general. (I am not telling you to stop commenting, but to write code which does not need trivial comments!)
See this question for more answers.
My rule of thumb is to include enough content to fully describe what the intent of the code is, and no more. In my opinion, assigning values to variables only to use those variables immediately is actually less readable. It communicates the flow of the program well enough, but doesn't communicate the actual intent.
If you renamed the function from dbReturn to GetDatabaseValue then I don't think I can come up with a more expressive way to write this function than:
return (GetDatabaseValue("NUns") / GetDatabaseValue("TSpd")) * 60);
This communicates the intent perfectly (notwithstanding the fact that I don't know what "NUns" and "TSpd" mean). Fewer symbols means fewer things to understand when reading the code.
Full disclosure: Including extra symbols does improve debuggability. I write this way when I am first building a function so that I can track down where things go wrong. But, when I am satisfied with the implementation, I compress it down as much as possible for my and my co-workers' sanity.
As far as I can tell, there would be no run-time performance gain achieved by either approach. Compilers are awesome - they do this inlining without your knowledge. The only difference is in the code's readability.
To me, longer is always better. Modern compilers will shrink most code to be very fast. However, being able to maintain code through lots of comments and easy-to-read code is hugely important.... especially if you are one of those guys who have to maintain someone else's code!
So, my vote is the longer version (with a comment explaining what you are doing too!)

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