Is it possible to return 0 inside a function in contract when the condition inside the require results to false?

contract MyContract {
     function initialize() public payable returns (uint) {
        require(10 ** 15 < msg.value); //return 0 if this fails
        return 1; //otherwise return 1
  • 2
    Why not use if, instead of require? Do you want to rollback all changes made in this call and return? Of that's the case it is not possible, you can't return any value if require criteria not met.
    – Yetik
    Commented Oct 10, 2022 at 5:37
  • 1
    In 2022 and later, consider using custom errors. Commented Oct 10, 2022 at 6:20

4 Answers 4


Well, you can try to use try-catch

Currently, Solidity supports different kinds of catch blocks depending on the type of error. If the error was caused by revert("reasonString") or require(false, "reasonString") (or an internal error that causes such an exception), then the catch clause of the type catch Error(string memory reason) will be executed.

Inside the catch block return the value you desire like in this example:

try initialize() returns (uint v) {
        return true;
    } catch Error(string memory /*reason*/) {
        // This is executed in case
        // revert was called inside initialize
        // and a reason string was provided.
        return false;

Because initialize is payable, you need to call it in the correct way with funds


No, if the require function is evaluated to false, nothing is returned because the code has stopped executing.

See: https://docs.soliditylang.org/en/v0.8.16/control-structures.html

  • Can it be done by catching the error? [From what I've figured out from documentation that try and catch only work for external calls, but I'm not sure about this case]
    – xrfxlp
    Commented Oct 10, 2022 at 4:48
  • No, because when an error occurs, the state is reverted back to its original state. Commented Oct 10, 2022 at 4:52


function throwErr() public {
require(err == true, "0");

if false, 0 will be displayed as the error message.

  • Sorry, my question was regarding returning not displaying. I'll update the question to make it clear.
    – xrfxlp
    Commented Oct 10, 2022 at 4:42

If you are calling an external function, you can use the try/catch structure to catch the error and return/log something different, like false indicating that there was a problem and probably also emitting an event. Because if you make changes to the state, emitting events, etc., and then an exception happens, all that will be reverted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.