rap-2-h
rap-2-h

Reputation: 31948

How to panic! in production

Panic! seems to be the right way to stop a program while in development mode. But one should not ship a program that displays such a message for an excepted error:

thread '<main>' panicked at 'error message: ()', x.rs:785

Is there any way to exit a program early with an error code, without displaying developer oriented text? I could use process::exit but I've read that it does not perform cleanup, so what should we use?

Upvotes: 2

Views: 644

Answers (1)

oli_obk
oli_obk

Reputation: 31163

panic! is not the right way to stop a program.

Its sole purpose is to abort when everything is about to go south and you have no way to recover. If you are expecting some wrong behaviour anywhere, use Result and recover from that behaviour by printing a nice message and cleanly exiting.

If you have panic!s or assert!ions in your code and they trigger, the message you showed is the only correct thing that should be displayed, because it's a bug in your code and there's no clean way to recover from a bug.

Note that panic! does not necessarily perform cleanup. If you panic, and another panic happens in a Drop impl, the program simply aborts. Also there's a setting for rustc that turns off the cleanup on panic and simply aborts on the panic!.

Upvotes: 7

Related Questions