Binette@lemmy.ml to Learn Programming@programming.devEnglish · 2 months agoIs it better to check if a file exists before trying to load it, or to try to load it, and catch the error and move on?message-squaremessage-square15fedilinkarrow-up123arrow-down10file-text
arrow-up123arrow-down1message-squareIs it better to check if a file exists before trying to load it, or to try to load it, and catch the error and move on?Binette@lemmy.ml to Learn Programming@programming.devEnglish · 2 months agomessage-square15fedilinkfile-text
minus-squareGetOffMyLan@programming.devlinkfedilinkarrow-up2·edit-22 months agoIt is an expensive operation as it needs to unwind the stack to get the stack trace. But if you’re checking a single file you won’t notice it. If you’re doing it in a tight loop it’ll be very noticeable. Checking the file exists also has a cost. I likely wouldn’t bother if I was saving a single file especially as there are other exceptions that could be thrown in the process.
It is an expensive operation as it needs to unwind the stack to get the stack trace.
But if you’re checking a single file you won’t notice it.
If you’re doing it in a tight loop it’ll be very noticeable.
Checking the file exists also has a cost.
I likely wouldn’t bother if I was saving a single file especially as there are other exceptions that could be thrown in the process.