Exception not being caught - c#

I have a very simple application, we feed it a list of our websites, and it does a parallel foreach on them and inside each action it does an http post to it.
Similar to below:
static int success = 0
static void Main(string[] args) {
try {
Parallel.ForEach(sites, site=> {
try{
if(DoWebPost(site)) {
Console.Write("Posted {0} - {1}", ++success, site);
}
} catch {}
});
} catch {}
}
I can't figure out why it will throw an OutOfMemoryException, let alone why that will cause the entire application to crash, and not just catch and continue.
EDIT: Not exactly sure where the exception occurs, since it doesn't locally, only when running in production... meaning no debugging available. The Application is 64bits, and rarely uses more than 100 megs.

In the words of Marc Gravell
If you "fix" your code by handling this exception you are burying your head in the sand.

You mentioned the code that is posted is somewhat the same as the code you used.
Can you actually post the full code or the exact code that is causing this.
Something tells me you have some sort of memory leak, you need to address this first.

Related

Why Dispose is not called even with using-statement?

I have this console application (.NET Framework 4.5.2):
class Program
{
static void Main(string[] args)
{
using (var result = new Result())
{
result.Test();
}
}
}
public class Result : IDisposable
{
public void Test()
{
int a = 1;
int b = 1 / (a - 1);
}
public void Dispose()
{
Console.WriteLine("Dispose");
}
}
Why Dispose method is not called? A breakpoint is not hit in Dispose after the DivideByZero-exception and there is no output on the console (because the app exits).
As per MS Docs: try-finally (C# Reference)
Within a handled exception, the associated finally block is guaranteed
to be run. However, if the exception is unhandled, execution of the
finally block is dependent on how the exception unwind operation is
triggered. That, in turn, is dependent on how your computer is set up.
As you are not catching the DivideByZero exception and let it be unhandled, on your machine and setup it must be bringing down the application before any other line of code is run and therefore not running the finally block.
As #Evk has pointed out in below comment, if I run it without attaching debugger, it unwinds the exceptions correctly and executes the finally block. Learn something new everyday.
As per Eric Lippert's answer to Finally Block Not Running?
Think about how awful that situation is: something unexpected has
happened that no one ever wrote code to handle. Is the right thing to
do in that situation to run even more code, that was probably also not
built to handle this situation? Possibly not. Often the right thing to
do here is to not attempt to run the finally blocks because doing so
will make a bad situation even worse. You already know the process is
going down; put it out of its misery immediately.
In a scenario where an unhandled exception is going to take down the
process, anything can happen. It is implementation-defined what
happens in this case: whether the error is reported to Windows error
reporting, whether a debugger starts up, and so on. The CLR is
perfectly within its rights to attempt to run finally blocks, and is
also perfectly within its rights to fail fast. In this scenario all
bets are off; different implementations can choose to do different
things.

Simulate Exception in Environment.Exit

A production console application that is shut down via Environment.Exit(0) every night prior midnight, occasionally experiences an exception during .Exit() which leaves the console application hanging, with an "Application has stopped working" screen.
This causes the process not to clean up properly and a relaunch after midnight fails because the prior process is still lingering.
Since I couldn't pin down what causes the exception in Environment.Exit, I'd like to at least handle it gracefully when it occurs and ensure that the process shuts down entirely. To do that, I'd like to simulate a crash after .Exit() but I wasn't able to find a scenario yet that would produce an exception during .Exit().
Does anyone have an idea how an exception during Environment.Exit could be simulated?
Sure, it's easy enough to duplicate:
private static void Main()
{
try
{
new ItsATrap();
Environment.Exit(0);
}
catch (Exception ex)
{
Console.WriteLine("During exit: {0}", ex);
}
}
private class ItsATrap
{
~ItsATrap()
{
throw new InvalidOperationException("Ooops!");
}
}
Note that the During exit text is never printed in the example above.
You can catch unhandled exceptions by installing a handler like this:
AppDomain.CurrentDomain.UnhandledException += (sender, args)
=> Console.WriteLine("Unhandled: {0}", args.ExceptionObject);
This way you have an opportunity to log them.
So... check your finalizers to see if they can throw.
Also, make sure they don't use other managed resources, as the finalization order isn't deterministic. As usual, Eric Lippert has some good articles to read on the subject.
You have an XY-problem here. You want to simulate an exception because you have no idea what else you could do. Instead of simulating something you don't exactly know, you should try to find out the real cause of the issue and fix it.
Collect a crash dump (MSDN) and load it into Visual Studio. As long as it's somewhere in your C# code, it should show you the line number.
See also: How do I take a good crash dump for .NET? here on Stack Overflow.
Modifying your code as proposed in other answers may change the timing and could just make the exception less likely or occur in different positions. Be happy that you can reproduce the problem and fix it instead of diluting it.
Use of a disposed/finalized object can probably cause it. This happens because there is no fixed order for finalization, so for example an hand-made logger that tries to write something on a Stream that has been finalized will cause an exception (hand made because "professional" loggers know of this :-) ).
You could try installing a first-chance exception handler just before calling the Environment.Exit that logs every exception that happens during this time. Something like:
object lck = new object();
AppDomain.CurrentDomain.FirstChanceException += (sender, e) =>
{
lock (lck)
{
File.AppendAllText("log.txt", string.Format("{0}: {1}", DateTime.Now, e.Exception.ToString()));
}
};
Environment.Exit(0);

System.NullReferenceException On WCF call

I'm having quite a difficulty trying to trace this bug. At first I thought it was linq SQL data that's causing NRE because every time I look at the tracer log, it gives me the .cs line 37 which is pointed to my sql (stored proc) call. The reason I suspect this, the result of this sproc is null (not NULL) but there's no row return for all the fields. What I did was to put data on it, and now comes the frustration; I still get the same error. Maybe it's worth mentioning that when I use the WCF as reference(not servicereferences) a DLL straight to bin then it works perfect, only when I try to use the client (mywebservice.client) one.
Any ideas where I should be looking? It is on app.config? Also, I'm using a console app to access the WCF.
This is my code:
public static List<usp_GetPaymentsResult> GetScheduledPayment(DateTime DateRun, int Fee)
{
try
{
PaymentDataContext DBContext = new PaymentDataContext();
return DBContext.usp_GetPayments(DateRun, Fee).ToList(); //line 37
}
catch (SqlException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
public static List<usp_GetPaymentsResult> GetScheduledPayment(DateTime DateRun, int Fee)
{
using(var context = new PaymentDataContext())
{
var payments = DBContext.usp_GetPayments(DateRun, Fee);
if (payments == null)
{
// bad database! handle error here
}
return payments.ToList();
}
}
Please note the following:
A DBContext is IDisposable. Put it in a using block, or it will
not be disposed in a timely fashion.
Your exception handling blocks did nothing but trash the exception.
If you want to rethrow an exception, use throw; without the
variable. It will rethrow the exception. Using the variable ex again
will overwrite it's stacktrace and valuable information will be lost.
However, as your blocks would have been nothing but rethrowing an
exception, you can just not catch it. Same result.
Check the result for null before you call an extention method like
.ToList() on it.
Finally, WCF Webservices are not magic. You can put breakpoints there and debug them. If you have problems doing so, maybe it would be a good idea to ask a question about that with more details about your webservice setup (VS internal or IIS Express or IIS?) and your project structure. Guessing the error based on line number is so 80s :)
After a frustrating 30 mins trying to debug a WCF NullReferenceException, turned out I had corrected an error in the WCF method structure, but hadn't refreshed the service in the calling client.

File.WriteAllText() runs OK, or does it?

I've been starting at this code for the best part of 2 hours (literally) but I can not seem to grasp why this would fail. This method below does not report any exceptions, yet it seems to return false:
public bool SaveFile(string filename, object source)
{
bool result = true;
StringBuilder exportText = new StringBuilder(source.ToString());
try {
File.WriteAllText(filename, exportText.ToString());
}
catch (Exception e)
{
OnPluginError(new ErrorEventArgs(e));
result = false;
}
return result;
}
The problem is: the file is properly written at the requested path, is complete, and readable. No exceptions are thrown, because the OnPluginError() handler invocation method isn't called - any message would be logged in that case, but there is nothing logged. It can't be a permission problem because the file does exist after the call.
And still, the method result is false.
The problem only appears in a Release build. In Debug builds, all seems to work OK. Hence, I can't use the debugger to step through.
This is called from a web application. Any ideas appreciated.
As a temporary troubleshooting step, add another try catch to block any exceptions and then see if the function is still returning false.
public bool SaveFile(string filename, object source)
{
bool result = true;
StringBuilder exportText = new StringBuilder(source.ToString());
try {
try {
File.WriteAllText(filename, exportText.ToString());
} catch(Exception e) { }
}
catch (Exception e)
{
OnPluginError(new ErrorEventArgs(e));
result = false;
}
return result;
}
If it is returning true, then you have isolated the problem and determined that an exception is being thrown, causing the block with result = false to be run.
If it is still returning false, then you can be certain the problem is outside of this function, as the rules of control flow would dictate that the result variable would never be changed.
One possibility is you have an issue with either the code you think is being run is not really being run. For example some issue with the build process not picking up your most recent code changes or redirection. Checking the versions of the website project DLLs, doing clean/rebuild, adding additoinal code to write out trace messages, are all things you should try to cross check to verify your most recent code is being run.
Another possibility is a problem in the code that is checking the return value.
Well...I do feel a bit silly here. I finally found the problem, and it is (as some posters questioned) not related to the WriteAllText() method at all.
FYI: this code ran deep inside an extensive plugin library. Not all that code was designed and written by me, and has been around for almost 2 years without running into problems.
As I mentioned, the WriteAllText() ran fine. It did. Problem was that the location of the file saved, was stored in a Dictionary, which in turn was requested from the plugin currently running. That Dictionary (containing plugin settings) turned out to be created from scratch with each call to that property! So I could add to it as much as I wanted....at the next call to that property, the newly added items would 'disappear' magically since the Dictionary was created anew.
Since it never surfaced before, and that code ran in a lot of other plugins with no problems, I didn't check that property. My bad.
Apologies to everyone that responded for wasting their time. Rest assured it won't happen any time soon! Lesson learned...

How does code look when you don't use exceptions to control flow?

I've taken the advice I've seen in other answered questions about when to throw exceptions but now my APIs have new noise. Instead of calling methods wrapped in try/catch blocks (vexing exceptions) I have out argument parameters with a collection of errors that may have occurred during processing. I understand why wrapping everything in a try/catch is a bad way to control the flow of an app but I rarely see code anywhere that reflects this idea.
That's why this whole thing seems so strange to me. It's a practice that is supposedly the right way to code but I don't see it anywhere. Added to that, I don't quite understand how to relate to client code when "bad" behavior has occured.
Here's a snippet of some code I'm hacking around with that deals with saving pictures that are uploaded by users of a web app. Don't sweat the details (it's ugly), just see the way I've added these output parameters to everything to get error messages.
public void Save(UserAccount account, UserSubmittedFile file, out IList<ErrorMessage> errors)
{
PictureData pictureData = _loader.GetPictureData(file, out errors);
if(errors.Any())
{
return;
}
pictureData.For(account);
_repo.Save(pictureData);
}
Is this the right idea? I can reasonably expect that a user submitted file is in some way invalid so I shouldn't throw an exception, however I'd like to know what was wrong with the file so I produce error messages. Likewise, any client that now consumes this save method will also want to find out what was wrong with the overall picture saving operation.
I had other ideas about returning some status object that contained a result and additional error messages but that feels weird. I know having out parameters everywhere is going to be hard to maintain/refactor/etc.
I would love some guidance on this!
EDIT: I think the user submitted files snippet may lead people to think of exceptions generated by loading invalid images and other "hard" errors. I think this code snippet is a better illustration of where I think the idea of throwing an exception is being discouraged.
With this I'm just saving a new user account. I do a state validation on the user account and then I hit the persistent store to find out if the username has been taken.
public UserAccount Create(UserAccount account, out IList<ErrorMessage> errors)
{
errors = _modelValidator.Validate(account);
if (errors.Any())
{
return null;
}
if (_userRepo.UsernameExists(account.Username))
{
errors.Add(new ErrorMessage("Username has already been registered."));
return null;
}
account = _userRepo.CreateUserAccount(account);
return account;
}
Should I throw some sort of validation exception? Or should I return error messages?
Despite the performance concerns, I think it's actually cleaner to allow Exceptions to be thrown out of a method. If there are any exceptions that can be handled within your method, you should handle them appropriately, but otherwise, let them bubble up.
Returning errors in out parameters, or returning status codes feels a bit clunky. Sometimes when faced with this situation, I try to imagine how the .NET framework would handle the errors. I don't believe there are many .NET framework methods that return errors in out parameters, or return status codes.
By definition, "exception" means an exceptional circumstance from which a routine cannot recover. In the example you provided, it looks like that means the image was invalid/corrupt/unreadable/etc. That should be thrown and bubbled up to the topmost layer, and there decide what to do with the exception. The exception itself contains the most complete information about what went wrong, which must be available at the upper levels.
When people say you should not use exceptions to control program flow, what they mean is: (for example) if a user tries to create an account but the account already exists, you should not throw an AccountExistsException and then catch it higher up in the application to be able to provide that feedback to the user, because the account already existing is not an exceptional case. You should expect that situation and handle it as part of your normal program flow. If you can't connect to the database, that is an exceptional case.
Part of the problem with your User Registration example is that you are trying to encapsulate too much into a single routine. If your method tries to do more than one thing, then you have to track the state of multiple things (hence things getting ugly, like lists of error messages). In this case, what you could do instead is:
UsernameStatus result = CheckUsernameStatus(username);
if(result == UsernameStatus.Available)
{
CreateUserAccount(username);
}
else
{
//update UI with appropriate message
}
enum UsernameStatus
{
Available=1,
Taken=2,
IllegalCharacters=3
}
Obviously this is a simplified example, but I hope the point is clear: your routines should only try to do one thing, and should have a limited/predictable scope of operation. That makes it easier to halt and redirect program flow to deal with various situations.
I think this is the wrong approach. Yes, it's very likely that you'll get occasional invalid images. But that's still the exceptional scenario. In my opinions, exceptions are the right choice here.
In situations like you have I usually throw a custom exception to the caller. I have a bit of a different view on exceptions maybe than others have: If the method couldn't do what it is intended to do (ie. What the method name says: Create a user account) then it should throw an exception - to me: not doing what you're supposed to do is exceptional.
For the example you posted, I'd have something like:
public UserAccount Create(UserAccount account)
{
if (_userRepo.UsernameExists(account.Username))
throw new UserNameAlreadyExistsException("username is already in use.");
else
return _userRepo.CreateUserAccount(account);
}
The benefit, for me at least, is that my UI is dumb. I just try/catch any function and messagebox the exception message like:
try
{
UserAccount newAccount = accountThingy.Create(account);
}
catch (UserNameAlreadyExistsException unaex)
{
MessageBox.Show(unaex.Message);
return; // or do whatever here to cancel proceeding
}
catch (SomeOtherCustomException socex)
{
MessageBox.Show(socex.Message);
return; // or do whatever here to cancel proceeding
}
// If this is as high up as an exception in the app should bubble up to,
// I'll catch Exception here too
This is similar in style to a lot of System.IO methods (http://msdn.microsoft.com/en-us/library/d62kzs03.aspx) for an example.
If it becomes a performance problem, then I'll refactor to something else later, but I've never needed to squeeze performance out of a business app because of exceptions.
I would allow for exceptions as well but based on your thread your looking for an alternative. Why not include a status or error information in your PictureData object. You can then just return the object with the errors in it and the other stuff left empty. Just a suggestion, but you are pretty much doing exactly what exceptions were made to solve :)
First off, exceptions should never be used as a control-flow mechanism. Exceptions are an error propagation and handling mechanism, but should never be used to control program flow. Control flow is the domain of conditional statements and loops. That is quite often a critical misconception that many programmers make, and is usually what leads to such nightmares when they try to deal with exceptions.
In a language like C# which offers structured exception handling, the idea is to allow 'exceptional' cases in your code to be identified, propagated, and eventually handled. Handling is generally left to the highest level of your application (i.e. a windows client with a UI and error dialogs, a web site with error pages, a logging facility in the message loop of a background service, etc.) Unlike Java, which uses checked exception handling, C# does not require you to specifically handle every single exception that may pass through your methods. On the contrary, trying to do so would undoubtedly lead to some severe performance bottlenecks, as catching, handling, and possibly re-throwing exceptions is costly business.
The general idea with exceptions in C# is that if they happen...and I stress if, because they are called exceptions due to the fact that during normal operation, you shouldn't be encountering any exceptional conditions, ...if they happen then you have the tools at your disposal to safely and cleanly recover and present the user (if there is one) with a notification of the applications failure and possible resolution options.
Most of the time, a well written C# application won't have that many try/catch blocks in core business logic, and will have a lot more try/finally, or better yet, using blocks. For most code, the concern in response to an exception is to recover nicely by releasing resources, locks, etc. and allowing the exception to continue on. In your higher level code, usually in the outer message processing loop of an application or in the standard event handler for systems like ASP.NET, you'll eventually perform your structured handling with a try/catch, possibly with multiple catch clauses to deal with specific errors that need unique handling.
If you are properly handling exceptions and building code that uses exceptions in an appropriate way, you shouldn't have to worry about lots of try/catch/finally blocks, return codes, or convoluted method signatures with lots of ref and out parameters. You should see code more like this:
public void ClientAppMessageLoop()
{
bool running = true;
while (running)
{
object inputData = GetInputFromUser();
try
{
ServiceLevelMethod(inputData);
}
catch (Exception ex)
{
// Error occurred, notify user and let them recover
}
}
}
// ...
public void ServiceLevelMethod(object someinput)
{
using (SomeComponentThatsDisposable blah = new SomeComponentThatsDisposable())
{
blah.PerformSomeActionThatMayFail(someinput);
} // Dispose() method on SomeComponentThatsDisposable is called here, critical resource freed regardless of exception
}
// ...
public class SomeComponentThatsDisposable: IDosposable
{
public void PErformSomeActionThatMayFail(object someinput)
{
// Get some critical resource here...
// OOPS: We forgot to check if someinput is null below, NullReferenceException!
int hash = someinput.GetHashCode();
Debug.WriteLine(hash);
}
public void Dispose()
{
GC.SuppressFinalize(this);
// Clean up critical resource if its not null here!
}
}
By following the above paradigm, you don't have a lot of messy try/catch code all over, but your still "protected" from exceptions that otherwise interrupt your normal program flow and bubble up to your higher-level exception handling code.
EDIT:
A good article that covers the intended use of exceptions, and why exceptions aren't checked in C#, is the following interview with Anders Heijlsberg, the chief architect of the C# language:
http://www.artima.com/intv/handcuffsP.html
EDIT 2:
To provide a better example that works with the code you posted, perhaps the following will be more useful. I'm guessing at some of the names, and doing things one of the ways I've encountered services implemented...so forgive any license I take:
public PictureDataService: IPictureDataService
{
public PictureDataService(RepositoryFactory repositoryFactory, LoaderFactory loaderFactory)
{
_repositoryFactory = repositoryFactory;
_loaderFactory = loaderFactory;
}
private readonly RepositoryFactory _repositoryFactory;
private readonly LoaderFactory _loaderFactory;
private PictureDataRepository _repo;
private PictureDataLoader _loader;
public void Save(UserAccount account, UserSubmittedFile file)
{
#region Validation
if (account == null) throw new ArgumentNullException("account");
if (file == null) throw new ArgumentNullException("file");
#endregion
using (PictureDataRepository repo = getRepository())
using (PictureDataLoader loader = getLoader())
{
PictureData pictureData = loader.GetPictureData(file);
pictureData.For(account);
repo.Save(pictureData);
} // Any exceptions cause repo and loader .Dispose() methods
// to be called, cleaning up their resources...the exception
// bubbles up to the client
}
private PictureDataRepository getRepository()
{
if (_repo == null)
{
_repo = _repositoryFactory.GetPictureDataRepository();
}
return _repo;
}
private PictureDataLoader getLoader()
{
if (_loader == null)
{
_loader = _loaderFactory.GetPictureDataLoader();
}
return _loader;
}
}
public class PictureDataRepository: IDisposable
{
public PictureDataRepository(ConnectionFactory connectionFactory)
{
}
private readonly ConnectionFactory _connectionFactory;
private Connection _connection;
// ... repository implementation ...
public void Dispose()
{
GC.SuppressFinalize(this);
_connection.Close();
_connection = null; // 'detatch' from this object so GC can clean it up faster
}
}
public class PictureDataLoader: IDisposable
{
// ... Similar implementation as PictureDataRepository ...
}

Categories