Panic, unreachable and Error in a library written for "non-programmers"

Hello everyone,

I'm writing a small/midsize simulation program (library+binary, maybe around 5 000-10 000 lines) for a research group. (The binary will contain things like reading the parameters, and setup of the simulations, so it might has to be changed during "normal" usage, e.g. if the content/structure of a parameter file changes.) And I'm not sure what would be the proper use of panics and errors.

Most probably it will be used only by them, and they will have full access to the source code, but they are mostly less experienced in programming. (Actually nor I'm a really experienced programmer.) So I would like to write the program as easy and (more importantly) safe to use (and extend) as possible. It won't be used in production, so crashes are mostly acceptable.

So I guess if some point of the program shouldn't be reachable (not even with improper use of the library, but only because of an actual bug in it) I should use unreachable!, to indicate that it's a bug.
But I'm not sure if I should panic when there is a logical error in the use of the library. For example most of the parameters should be set (from parameter files) once at the beginning of a run. So I was thinking about if it's OK to panic if the user tries to set any of these parameters twice. (Because it is a potential source of bugs.) So he/she can't "ignore" the returned Error message (by accident or by purpose) e.g. the following way:
match result { Ok(_) => {/*DO SOME STUFF*/}, Err(_) => {/*DO NOTHING*/} }

+1: Does it change anything, if later there would be a "public release" after all. So that other reserach groups might use the program as well, where they not necessarily wants to know the very fine details of the library, just use the public interface in the binary. (Or just want to use the provided binary as is, and only modify the (relevant) input file(s).)

As long as you explain what they did wrong, crashing is OK. You may also ask the user, if the program should continue either way,in the case of duplicate definitions.

1 Like

I think I would go with liberal use of anyhow in this situation. It makes creating/propagating/handling errors pretty easy and allows you to attach relevant information to the error in a straightforward manner. If you make the return type of all fallible functions anyhow::Result, the programmer can "handle" the error with result? or result.context("operation X failed!")?. By making the proper error handling easier it should hopefully discourage the mishandling you were worried about in the OP.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.