What exception class to use in when IEnumerable contains null [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 seen the following exception case several times
public SomeClass(IEnumerable<T> someValues)
{
if (null == someValues)
{
throw new ArgumentNullException("someValues");
}
int counter = 0;
foreach (T value in someValues)
{
if (null == value)
{
string msg = counter + "th value was null";
// What exception class to use?
throw new ArgumentException(msg, "someValues");
}
counter++;
}
}
Is there a guideline for handling these cases? And in general is there any guidelines describing "exception style" a bit more detailed than the MSDN documentation for
Exception
ArgumentException

Throw ArgumentNullException if there was a null argument.
Throw ArgumentOutOfRange exception if there was an argument out of its range (like a negative number where only positive numbers were expected.)
Throw ArgumentException if the argument was invalid for a reason other than it was out of range or null.
Throw InvalidOperationException if the call was invalid for a reason not pertaining specifically to a value of an argument.
In this particular case I'd probably choose ArgumentException. The argument is invalid because its contents are invalid.
Of course, all of these are exceptions which indicate that the caller has a bug. It's a good habit to give the best possible error so that the author of the buggy caller can rapidly diagnose the problem. I'd therefore consider also adding a custom message to the exception saying "element of sequence blah was unexpectedly null" or some such thing.

Yes there is, as described here, you should throw framework exceptions when possible and throwing the most derived exception that is applicable. In this case ArgumentNullException is thrown because an argument is null and ArgumentException is thrown because the contents of the enumeration are not directly a parameter of the function, so what you can say is that the argument is invalid, but it is not because it i null or is out of range.
If knowing why it is invalid becomes absolutely necessary you could derive from Argument Exception; something like ArgumentCollectionContainsNullException.

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.

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.

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?

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.

What is better: int.TryParse or try { int.Parse() } catch [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 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.

Categories