Using try catch even if no exception is expected [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 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.

Related

what's the best approach the return result or error [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 1 year ago.
Improve this question
lets say i have this method that call an API and return some results :
public async Task<List<ClientModel>> GetClients()
{
var result = new List<ClientModel>();
try
{
results = await myHttpCLient.GetFromJsonAsync<List<ClientModel>>("Api/Clients");
}
catch (Exception e)
{
// Something unexpected went wrong.
}
return results;
}
what's the best way to notify the caller in case something went wrong and send back the exception, and if no exception return the expected result, what do you guys use in scenarios like this , i know ref or out may solve this but is this a good design ?
what's the best way to notify the caller in case something went wrong and send back the exception, and if no exception return the expected result
Just get rid of the try-catch. This:
public async Task<List<ClientModel>> GetClients()
{
return await myHttpCLient.GetFromJsonAsync<List<ClientModel>>("Api/Clients");
}
will do exactly what you want:
If everything was OK, the expected result is returned, but
if an unexpected error occurred, the execption is automatically "bubbled up" to the caller of the method. The .NET Runtime takes care of that, you don't need to do anything.
Of course, if you want, you can catch the exception and wrap it in a custom MyApiCallFailedException. This, however, is only required if you want to handle it differently from other exceptions at your UI-level global exception handler.

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.

Catch specific exception vs general 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 7 years ago.
Improve this question
One of my co-worker asked what exception would I get if you execute a query that has a wrong table name. I was not able to answer since I always catch exceptions like the code below,
try
{
ExecuteQuery();
}
catch(Exception ex)
{
//show an error message
}
so I do not know what kind of error will be raised until it actually happens. But I like to code in this way because I can simply copy and paste that catch block at anywhere that needs to be try and catch blocked.
My question is that is it important to know what exceptions will be thrown and try to make as many specific catch exceptions as possible?
My question is that is it important to know what exceptions will be
thrown and try to make as many specific catch exceptions as possible?
It depends. If you are going to catch and handle specific exception then it makes sense to catch specific exception first and then the base exception.
One example could be to determine insertion of duplicate primary key, where you want the user to enter different value since the table can't allow insertion of duplicate key. In that case you will catch SqlException first and then have another block of Exception to catch any other.
try
{
ExecuteQuery();
}
catch (SqlException sqlException)
{
if (sqlException.Number == 2627) //duplicate key
{
// ask user to enter new value, repeat `ExecuteQuery`
}
}
catch (Exception ex)
{
//show an error message
}
Without catching SqlException you will not have access to Number field which has details about the particular SqlException.
(by the way, the above code is just an example to catch and handle specific exception, insertion of duplicate key can be avoided by checking the value first in table).
It depends. But generally, it is good to catch specific exceptions if you wish your application to behave differently under different circumstances. For example, a FileNotFoundException could tell you that your user needs to verify a path. General catch blocks are useful at the highest level of your application, but getting more specific further down the line allows you better control over how to respond to specific problems.
It is important if you want to show some personalized message about the exception to the user. For example: if it is a NullException, it shows a message with some code, for example 5504. And this number he/she says to helpdesk to inform about the problem. An article about this is here

Catching generic non-fatal 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 9 years ago.
Improve this question
Conventional wisdom suggests we should only catch the specific exception types we're expecting:
try
{
int.Parse(str); //I am aware of TryParse(), this is just for the sake of example
}
catch (FormatException ex)
{
Console.WriteLine (ex);
}
catch (OverflowException ex)
{
Console.WriteLine (ex);
}
However, sometimes we don't really care which exception happened (as long as it's not fatal), maybe because we just want to let the user know an error occurred. In these cases we can do something like this:
try
{
Foo();
}
catch (Exception ex)
{
if (IsCriticalException(ex))
{
Environment.FailFast("System Error", ex);
}
Console.WriteLine ("Error running Foo: {0}", ex);
}
Where IsCriticalException can be implemented similarly to System.ClientUtils.IsCriticalException. I am generally in favor of this approach for a couple of reasons:
Some methods can throw many exception types and it can be cumbersome to catch them all. For example, File.Open can throw nine different types of exceptions.
Some methods can throw undocumented exceptions. This is either due to lacking documentation, or due to some bug. For example, ICommunicationObject.Close can actually throw ArgumentException due to an obscure bug. Some methods cannot even know statically which exceptions could be thrown by them, since they load other modules / plugins dynamically. Supposedly they could wrap all such "external" exceptions with their own known exceptions, but I believe not all of them do.
The critics of this approach argue that a method's exceptions are part of its contract. If an exception is thrown that is not part of this contract, we should assume its state is corrupt. We will have also discovered a bug in the method (one we otherwise would not have spotted since we'd have swallowed the unexpected exception). We could then relay this bug to the framework's developers, and this is a win - especially if those developers are in our company, so we've "helped ourselves" so to speak.
I admit, the critics present valid points, but I feel they are a bit idealistic. Practically, I think generic non-fatal exception catching makes sense in a lot of situations. Am I making sense?
Related reading:
How to Design Exception Hierarchies
Vexing exceptions
Conventional wisdom suggests we should only catch the specific exception types we're expecting
Actually, I think you should catch exactly those exceptions, that you can handle. There is no use in catching exceptions just to rethrow them and it does not make sense to let those exceptions pass that you would have had a cure for.
In your above example, I think having a catch-all block would have been fine, after all not converting that string is a recoverable error, no matter what exception pops up (except for OutOfMemoryException, which cannot be handled anyway because any attempt at handling would use memory).

What exception class to use in when IEnumerable contains null [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 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.

Categories