简体   繁体   中英

Returning Meaningful Errors From C++ Function - Best Practice

I'm writing a class that has functions that can return multiple different types of errors depending on what point the function(s) stop working. As it stands now I don't have a formal idea of how to do this, but I've seen something similar to:

bool thisFunctionReturnsError(type param1, type param2, returntype& return)

This works, it returns true/false if an error occurs and otherwise will return a valid "returntype" into the return variable for the programmer to use. But my question is - is this the best practice?

I found the below topic but it's in regards to C. I'm curious if C++ has a better way to do this that doesn't involve exceptions (because they're not standard).

What is the best way to return an error from a function when I'm already returning a value?

Can anyone give me some advice on this? Thank you!

Technically if the error is something that shouldn't happen in normal operation, this is what C++ expects you to use exceptions for, and they are as standard as anything else in C++.

However, if the error may be a part of normal program flow, or if due to performance exceptions are not an option, consider returning a std::pair , or std::optional (C++14 or boost) if just the fail/succeed information is needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM