Catching generic non-fatal exceptions [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
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).

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.

Is logging an exception into a MessageBox a good practice? [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
I work on a team with a bunch of programmers who have a background in Java and Eclipse. Now in the project we work on in the C# code i see this code almost everywhere and most the times MUCH bigger:
try{
var result = WebService.GetUser("John Cena");
MyLabel.Text = result.Username;
}
catch(Exception e){
MessageBox.Show(e);
}
above would fail if the webservice crashed(unless it's atomic), or if the result is null.
I would prefer the exception thrown in VS editor rather than a messagebox with no tracing. I'm advising everyone on the team to NEVER EVER use a try catch block. Mainly because they abuse them.
I would like to hear some professional advice on how exceptions should/shouldn't be handled.
No, logging all exceptions in MessabeBox is bad practice. For example, you'll get NullReferenceException and show it to user. And what? Whant user should do? Does he know, what is NullReferenceException? What usefull information he will get? Zero.
You must log all exceptions in some storage, but show only "business" errors. For example: "You have no permission" and so on.
NullReferenceException is very low level exception to show it in message box.
Read more about exception handling strategies.
Logging exceptions in message boxes are ugly and not user friendly.
For Back-end code we do like this;
try
{
DoSomething();
}
catch (Exception ex)
{
//Logs all details of the exception including full stack trace..
ExceptionManager.LogError("Exception occured on 'DoSomething' method", ex);
}
For GUI;
try
{
DoSomething();
}
catch (Exception ex)
{
//Custom form to show all details of the exception
(new formExceptionHandller(ex, ex.Message)).ShowDialog();
}
Log all exceptions
Show only a standard error message to the user
Also make sure that the logged message is notified to the relevant technical-group, which can either be automated (right after logging) or on user reporting (give an option to the user to "report to admin" kind of thing)

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

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.

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