daw_json_link icon indicating copy to clipboard operation
daw_json_link copied to clipboard

daw::read_file is noexcept but calls std::filesystem::file_size which throws on missing files

Open marcelomatus opened this issue 9 months ago • 2 comments

Title: daw::read_file is noexcept but calls std::filesystem::file_size which throws on missing files

Body:

daw::read_file in include/daw/daw_read_file.h is declared noexcept, but its first line calls std::filesystem::file_size(path):

C++ template DAW_ATTRIB_NOINLINE std::optional<std::basic_string> read_file( std::string const &path ) noexcept { auto const fsize = std::filesystem::file_size( path ); // throws if file missing!

When path does not exist, std::filesystem::file_size throws std::filesystem::filesystem_error. Because the function is noexcept, the C++ runtime calls std::terminate() immediately — the exception cannot be caught by any surrounding try/catch. This makes it impossible to gracefully handle a missing file.

Suggested fix: Use the std::error_code overload so no exception is thrown:

C++ std::error_code ec; auto const fsize = std::filesystem::file_size( path, ec ); if( ec ) { return std::nullopt; }

marcelomatus avatar Feb 20 '26 03:02 marcelomatus

Thanks for finding that, it was a mistake to mark them noexcept and was missed. I don't want to change the interface as these are generally used in quick tests and ignoring the errors would be not great either, so letting them throw is the path of least resistance.

It will be fixed in https://github.com/beached/header_libraries/pull/564

Not sure how you integrate JSON Link, but it should already pull in the fixed version from the v2 branch of the header_libraries repo if using git. If vcpkg/conan/... it may take a bit to see those updated

beached avatar Feb 20 '26 04:02 beached

Thanks!, I´ll test it when available. In the meantime, I am checking before calling read_file. Thanks again

marcelomatus avatar Feb 23 '26 20:02 marcelomatus