Quoting 'Code Complete'
Use [exit] when it enhances readability In certain routines, once
you know the answer, you want to [exit] to the calling routine
immediately. If the routine is defined in such a way that it doesn’t
require any further cleanup once it detects an error, not [exiting]
immediately means that you have to write more code.
So normally one exit is preferred (people looking at your code don't have to find the correct exit statement), however with error checking (especially at the start of a program/routine having multiple exit statements is clearer.
Your example is borderline, however I would say that the second is preferred so that maintenance to your program/script can leave it tidy.
Your program currently is (in psudocode)
if error condition 1
// Show error message 1
else
// Do stuff
fi
or
if error condition 1
// Show error message 1
// exit
fi
// Do stuff
Once your program has grown, you realise some more ways that the program can fail. Your program now becomes
if error condition 1
// Show error message 1
else
if error condition 2
// Show error message 2
else
if error condition 3
// Show error message 3
else
// Do stuff
fi
fi
fi
or maybe
if error condition 1
// Show error message 1
else if error condition 2
// Show error message 2
else if error condition 3
// Show error message 3
else
// Do stuff
fi
versus
if error condition 1
// Show error message 1
// exit
else if error condition 2
// Show error message 2
// exit
else if error condition 3
// Show error message 3
// exit
fi
// Do stuff
In my mind, the last one is the clearest in being able to spot which is the error cases and which is the main flow of the program. Now add returning different values (eg. 0 on success, 1 on error 1, 2 on error 2, etc.) and the difference will become more pronounced.
exit
would be a recommended practice. in the abs-guide, for example, most scripts ends withexit 0
.