If you were designing a standard library of a high level language (like Rust, C++, etc.) what would it do if while getting the current time of day (e.g. SystemTime::now()
) it encountered a failed kernel system call (e.g. to clock_gettime
) and why?
What do you think the existing implementations do?
- Return error or raise exception
- Return 0
- Return undefined values (like stack garbage)
- Panic/crash/segfault
you should do what’s idiomatic for that language, e.g.: return an error in Rust; raise an exception in Python or Java; return an integer != 0 in C; etc.
Panic/crash/segfault
probably the worst option for a library
+1. If your library makes it impossible to recover from errors, then it will be unusable from any program that requires recovering from errors.
probably the worst option for a library
Even worse than returning garbage? :)
If it’s garbage as in a string with a bunch of information that is hard to parse, yeah, crashing without giving the caller a way to avoid it might be worse. But what is exactly this garbage and in what cases are you considering returning it at all?
Uninitialized automatic variables. E.g. (in C/C++):
int get_time() { int time; syscall(/* something that fails */, &time); return time; }
Raising an exception would be standard practice, IMO. A library should not dictate how an application behaves. Let the application handle it.
For Rust, return Result<> , as is idomatic in Rust.
Another possible method is having an installable handler that handles the error at the place it is detected. Common Lisp does that and it is very powerful.
Rust seems to think panicking is better: https://github.com/rust-lang/rust/issues/115482
Return an error, respectively, in a language that supports it, raise an exception.
In my systems, nearly every call returns a status, and it is advisable to check this status. I had a number of long calls with windows programmers who complained about my system failing at some point, and most often, the reason was an ignored Non-OK status return at some point in the past.
Like “Your system loses the file I’m writing!”. FileSystem_Open() returned a non-OK value (I don’t remember the reason, but there was one). FileSystem_Write() returned a non-OK value (file pointer invalid). FileSystem_Close() returned a non-OK value (file pointer invalid). And he complains about a file that is not there…