C++ best error handling practice?

So I’ve been learning C++ the last few months, and given that I have certain values that are specified by designers exposed on a given class, I need to validate and ensure that these values aren’t nullptrs.

Right now, the way I’m handling it is a large if statement - I’m trying to effectively log to the user which of these classes are unset. Is there a better way to handle/do this?

I’d really appreciate any help here!

Make a CHECK_NULL() with one parameter that accepts a reference. If that reference is null, output to log and return. Its usage will look like:

CHECK_NULL(LilyCharacter, LilySceneTransition, "Invalid Lily Player Character on Game Mode");
CHECK_NULL(PlayerCameraManager, LilySceneTransition, "Invalid Player Camera Manager");
... etc.

You can add parameters and have it in a well-used header file… or you could simply define one per cpp file that has class-specific data baked in. That depends on how you want to architect your code.

Its declaration will look something like:

#define CHECK_NULL(myPointer, myLogClass, myMessage) if(myPointer) UE_LOG(myLogClass, Error, TEXT(myMessage), *this->GetFName()->toString()); return

Make sure that’s all one line!

Sorry I didn’t test it (I came across your tweet but didn’t have my PC setup correctly) but yeah. Hope this helps.

1 Like

This works absolutely perfectly, just a minor typo on ToString() in the macro definition. And now I know how to use Macros!

For prosperity, another suggestion on this twitter was to use checkf or ensure - more documentation is found here: Asserts | Unreal Engine Documentation

But now I know how to define macros, and honestly for this project I love now having simple definitions for checking validity. Thanks, Scott! :slight_smile: