diff --git a/bob/io/base/file.cpp b/bob/io/base/file.cpp
index 8856bacc70ce7f660b786ac49a9588d7fa3067a6..fc2622a7efb5f595b8f0fdf33094b4e4b285fe36 100644
--- a/bob/io/base/file.cpp
+++ b/bob/io/base/file.cpp
@@ -73,12 +73,14 @@ int PyBobIo_FilenameConverter (PyObject* o, const char** b) {
     *b = PyUnicode_AsUTF8(o);
   } else {
     PyObject* temp = PyObject_Bytes(o);
+    if (!temp) return 0;
     auto temp_ = make_safe(temp);
     *b = PyBytes_AsString(temp);
   }
 #else
   if (PyUnicode_Check(o)) {
     PyObject* temp = PyUnicode_AsEncodedString(o, Py_FileSystemDefaultEncoding, "strict");
+    if (!temp) return 0;
     auto temp_ = make_safe(temp);
     *b = PyString_AsString(temp);
   } else {