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)
Related
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.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm working with code I did not write that uses Entity Framework, which is still a bit of a mystery. In a web api controller there is the code below.
try
{
sdf = sdf.sdf(sdf);
}
catch (Exception ex)
{
return NotFound();
}
GetOrderByAlternateIdentifier throws a null pointer exception when a bad orderid comes in. This halts code execution in the GetOrderByAlternateIdentifier method because the error is not trapped. I would think that my try catch above would trap it so I can send back the NotFound response, but it doesn't.
How can I get my try catch to catch the error that occurs in GetOrderByAlternateIdentifier()?
Greg
Exceptions do not halt code. My best guess at what is happening is that the Visual Studio debugger is breaking when exceptions are thrown. There is a setting that determines whether or not this happens.
However, when you are not debugging, exceptions will not halt the code. And try...catch works fine. It's well tested.
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
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).
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.