Is it possible for current_dir() to return Err?

I'm using std::env::current_dir().unwrap() in different places of my code. Is that usually OK, like, will it ever be Err? Any special occasion?

current_dir in std::env - Rust explains cases where it's Err, but do they happen usually? Should I worry about this?

They certainly can happen, but they all indicate that something bad has happened to the filesystem after the program started: Either the user has done something like delete the directory, or there’s been a hardware failure.

If your program is expected to run unassisted, there’s not much you can do to recover— panicing is often the only reasonable course. On the other hand, if you have some kind of interactive session with the user, you can ask them for a different directory to switch to.


It can also happen if you have a program that runs as another user or otherwise drops permissions (like some sort of daemon), but yeah it's rare.


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.