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.
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 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)
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 needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to make a C# (Windows Forms) application which utilizes SQLite. Anyway, my code is this :
try
{
db.Insert("COLUMN_NAME", data);
}
catch (Exception e)
{
//MessageBox.Show(e.Message);
}
I made COLUMN_NAME unique, so it throws an SQL error, intentionally. But I don't want to see the error message in a MessageBox, so I commented out the MessageBox.Show() line, but still the error message pops up. Is it a property of try / catch ? If so, how can I prevent it ?
P.S.
I know there are better ways to do this task, but it is not important. I just want to learn how to get rid of error messages in exceptions.
Thanks for any help !
I figured the problem. The line db.Insert(); itself has a try/catch block, which shows a MessageBox.
I found the code here by the way.
Thanks again for all the help !
There is RunTime error in your line at
db.Insert("COLUMN_NAME", data);
So you need to fix this.
Try by clean and then build your code. Then run the code. Sometimes dll file is not refreshed. It will be regeneratedby clean and build your code.
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.