I could use inre error handling in kotlin native. ...
# kotlin-native
a
I could use inre error handling in kotlin native. I'm trying to enumerate the contents of a directory with
readdir
from
dirent.h
. I have the following code:
Copy code
while (true) {
                    val ep = readdir (dp)
                    if (ep == null) break
                    val str = ep.pointed.d_name.toKString()
                    println(str)
                }
This works for some dirs but not all. On some, I get the following partway through the enumeration:
Copy code
terminate called after throwing an instance of 'utf8::invalid_utf8'
  what():  Invalid UTF-8
The execution terminates immediately. How do I catch/recover from this error? I've tried wrapping with try/catch Throwable to no avail.
Hacky but working workaround:
Copy code
while (true) {
    val ep = readdir (dp)
    if (ep == null) break
    val str = ep.pointed.d_name.run {
        generateSequence(0) { it + 1 }
                .map { this[it] }
                .takeWhile { it.toInt() != 0 }
                .joinToString("") { it.toChar().toString() }
    }
    println(str)
}
Surely there must be a better way? 😛
t
Unix makes no guarantees that filenames will be valid strings in any encoding – they can be any sequence of bytes excluding slash and nul – so I think you have to either 1) treat them as opaque byte sequences (not strings); or 2) invent some crazy encoding scheme for invalid strings, like Python did: https://www.python.org/dev/peps/pep-0383/ 😩
a
Thanks Henrik! I learned something today.:) Still would be nice to know if it would be possible to recover from that exception? (as try/catch didn't seem to work)
t
Hm... I get a segmentation fault instead. It seems
toKString()
ends up calling the C++ function
utf8to16
in runtime/src/main/cpp/utf8/ which exists in a checked and an unchecked version, the former of which throws a C++ exception. So... I dunno. 🙂