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:
System.OutOfMemoryException
System.InvalidOperationException
with appropiate textWhich one is the best and why?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With