✅ Exception Handling for NRE without modifying every call.
I have a ReadData function which reads the memory of a process. If the process exits or crashes during the read, an exception is thrown and control is handed to the catch block. However, the calling function (the function that calls ReadData) can sometimes throw an NRE if the ReadData was aborted and returned null instead of a byte[]. How can I avoid the NREs without needing to change every single call of ReadData? Ideally I would abort the calling function as if it had never been called but I know that would require a large scale rewrite. I have toyed with the idea of modifying the ReadData signature to return a tuple of type (byte[], bool) and changing the behaviour of the calling function depending on the success of the ReadData (bool) but this would also require custom behaviour for every call. There are about 20 calls and I figure adding custom behaviour or exception handling for all of them is inefficient and bad practice. Any solutions?
17 Replies
ReadData
should really just be
no throwing involved
and you know immediately whether or not the call failed or succeeded from the return value
you could even make it an extension method on Process
;
and then you can simply do
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.I like this solution and I'm going to try it but I'm confused by the line
bufferSize is never declared?
ah, my bad
i just copy pasted the code from another method
Thank you, there's also a clash between my current declaration of the ReadProcessMemory method and the call to it. I'm assuming I need to change my declaration's signature?
yes
https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-readprocessmemory
this is the real signature
HANDLE
can be a nint
(or IntPtr
, they're identical, nint
just doesn't require using System;
)
LPVOID
and LPCVOID
are void*
SIZE_T
is nuint
(or UIntPtr
)
oh yeah and BOOL
is int
so the c# signature is
Thank you. I guess I need to declare the method as unsafe too
ah, yeah
or the class
better option
or
WinApi
or Win32Api
or use CsWin32
(NuGet)this seems to work. Sorry to be a pain but I assume there is also a solution for the write function which is similar?
almost the exact same
Thank you, I'll figure that one out
oh damn. Thank you 🙂
i'm not sure whether the handle check might be pointless
you can possibly just remove that one
^ it's not for my use case. I'll get on implementing this and hope it's less overhead and things speed up. Otherwise I have the nasty task of figuring out what's slowing my app down