Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is throwing OutOfMemoryException from application code good design

Tags:

c#

.net

exception

I remeber i read somewhere that throwing any of the System.SystemException derived exceptions from user code is a bad practice, as user code should only throw application exceptions.

We have an native library that uses the GPU. It may return an error code that indicates that we`re out of GPU memory. We want to translate this error code to a .Net exception.

This are the possible exceptions i can think of:

  1. System.OutOfMemoryException
  2. System.InvalidOperationException with appropiate text
  3. Custom exception (based on InvalidOperationException)

Which one is the best and why?

like image 324
sanosdole Avatar asked Sep 06 '25 17:09

sanosdole


2 Answers

Throwing System.OutOfMemoryException is not an ideal choice. Programmers who use your library may potentially react to System.OutOfMemoryException by purging some of their non-essential objects from memory, and trying again. However, in your case it is GPU memory, not system memory, so their attempt wouldn't have a chance to work.

If users have an option to unload things from GPU memory, directly or indirectly, custom exception approach (number three) provides the cleanest choice. If they have absolutely no control over it, i.e. the exception is basically a "you're dead" message, then System.InvalidOperationException is a good choice as well.

like image 184
Sergey Kalinichenko Avatar answered Sep 09 '25 15:09

Sergey Kalinichenko


Raising an OutOfMemoryException is the worst choice. The reason for this is that this exception is almost impossible to recover from in the general case and for a client, it is extremely hard to determine whether the system ran out of memory or you just abused this exception type, especially because the client will not expect this behavior.

Raising an InvalidOperationException is a better thing, because the client will be able to handle this (by offloading the computation to somewhere else or performing the required stuff in the CPU, potentially using a different library). However, if the exception is an InvalidOperationException, this exception type is most likely used also by other libraries or used by the BCL. Thus, the client has to react to this exception by parsing the error message, which is not reliable.

Therefore, the best solution would be a custom exception type, because this will enable clients to just catch this exception type and recover from this situation or tell the user what the problem is. Whether or not you feel that this is a special case of an invalid operation is up to you. Personally, I would not let the exception inherit from InvalidOperationException but from Exception directly.

like image 21
Georg Avatar answered Sep 09 '25 16:09

Georg