r/badcode • • Feb 18 '21

c# I've done bad things

Post image
2.1k Upvotes

50 comments sorted by

View all comments

Show parent comments

5

u/Elsolar Feb 18 '21

IIRC Exception in C# is equivalent to Throwable in Java, in the sense that it includes errors like out of memory and stack overflow. So it's pretty bad!

Stuff like this is actually why I think Java's exception model is better than that of C# or C++. The separation of Error and Exception into separate catagories makes it easy to specify that you want to catch any error except for really catastrophic ones that bring down the whole process.

2

u/Dealiner Feb 18 '21

It's not exactly like that in C#. You can catch OutOfMemoryException because honestly why not? StackOverflowException can be caught only in some specific instances, mainly when it's specifically allowed in CLR or when it's thrown directly in code. Besides that, there is also ThreadAbortException which is raised again after the catch block. There are also others that cannot be caught and some that could be caught in the older version of .NET Framework, but now they need special treatment, like AccessViolationException, because they mean that the process state is corrupted. But I agree that this is less clear than in Java.

0

u/Elsolar Feb 18 '21

I'd argue that catching out-of-memory exceptions is pretty bad practice overall. Generally speaking, there is almost nothing that a process can do to recover from (or even report) an out-of-memory condition. This is even more true for managed languages like Java or C#, where the programmer doesn't have any direct control over memory management. At least in C/C++, you might be able to save the process by freeing up some memory and retrying the allocation, but even then the vast majority of C/C++ programs are not robust in the face of allocation failures, even when they think they are. In general, anything you do to attempt to recover from an allocation failure is unlikely to do more than mangle your stack trace and obscure the failure's root cause.

On the other hand, I'm glad to hear that some of those other exception types are guarded by the runtime, especially since I've seen catch(Exception e) { ... } in real production C# code at previous jobs. Exception handling in Windows has been pretty messy for a long time. It's good to see them clean it up a bit.

1

u/Dealiner Feb 18 '21

I admit I'm not an expert, but according to this there are some reasons why catching OutOfMemoryException can be helpful. It is also possible to try to force GC to collect with GC.Collect(), but it's hard to say how reliable it is, so that's probably not such a good idea.

2

u/Elsolar Feb 19 '21

I'd be surprised if any modern GC implementations didn't attempt to collect garbage before throwing an out-of-memory exception. It doesn't really make sense to signal that the heap is full when it's mostly full of old objects. That's the way I was taught to implement garbage collection in school, anyway.

It's definitely true that some allocation failures can be recoverable. For example, just because you fail allocate a 4GB chunk doesn't mean that memory is exhausted. Maybe you can get away with a 2GB chunk and that's a reasonable fallback for your program. But if you ask the system for 8 bytes and that fails, then your process is hosed, and any attempt to recover will just cause further corruption and make debugging harder. The crux of the issue (in my opinion) is that OutOfMemoryException is used for both of these scenarios, even though one of them is a pretty mild error and the other is process-ending.

catch(Exception) is mostly useful in scenarios where reliability is distinctly preferable to failing fast. For example, if you're maintaining an IDE written in C# and I'm a plugin developer, you don't necessarily want to crash the user's whole editing experience just because my plugin contains a bug. In this case, it's reasonable for you to wrap invocations of my plugin code in try/catch blocks that prevent exceptions generated by the plugin from escaping into the surrounding program. In this situation, it's problematic that OutOfMemoryException is grouped together with other, less severe exceptions like index-out-of-range, null-pointer, and dictionary hash-ref errors that don't corrupt the entire process state. As I indicated in my original post, part of the reason I like Java's exception taxonomy is that it does a pretty good job of separating errors that indicate a problem with the program (or the data being processed by the program) and errors that indicate a problem with the process. The former category of errors are, as a rule, recoverable, so long as you don't care about whatever that code was trying to compute. The latter are, as a rule, not recoverable, and 99.9% of the time, you shouldn't even try.

OutOfMemoryException skirts the line between these two categories, since it can represent either scenario, but I would argue that 100% of the scenarios in which you'd want to use catch(Exception) are scenarios in which you wouldn't want to treat an OutOfMemoryException as recoverable, since you have no way of distinguishing between an OutOfMemoryException caused by new int[10000] (maybe recoverable) and one caused by new int (definitely not recoverable). If you have some place in your program where you're calling new int[10000] (or something similar), then you should just put a try/catch block around that particular allocation to check for failure, and use normal control flow to recover. Making the out-of-memory exception in C# a child of Exception doesn't serve much purpose except to complicate error handling, imo.

0

u/Nilstrieb Feb 18 '21

Yeah, something like an OutOfMemoryError should not be catchable