DEV Community

Discussion on: Exception handling explained

Collapse
 
jgauffin profile image
Jonas Gauffin • Edited

I was used to C/C++ way of thinking and coding and i had quite a surprise when my application crashed because it needed to list files from a folder that did not existed

If the folder should exist (created/handled by the code) it is an exception if it do not exist. Because the rest of that code can not function properly without it.

If it is expected that the directory may not exist, it's actually a bug if you do not use Directory.Exists before using the folder. If you only had got an error code it would have been much harder to understand what went wrong. (If you do not check if the directory exists you would typically not have checked for an "directory not found" error code).

I find that if you're forced to wrap every piece of code that can break in a try {} catch() block, your entire flow of thinking breaks and your code actually becomes harder to read and follow.

You should not wrap every part of the code with try/catch. That's the point. They are there to safeguard that your application don't save invalid results when something goes wrong.

If you can't handle the exception, you should not catch it. Most programming languages/frameworks that use exceptions have global hooks where you can catch them instead of polluting your entire application with try/catch blocks.