DEV Community

Discussion on: Exception handling explained

Collapse
 
adriannull profile image
adriannull

I'm sorry but i find this way of using exceptions extremely confusing and i find that it really breaks the flow of thinking about the code.

Error codes can be made to be verry clear about the problem they are signaling, if you define one value for every possible problem you could encounter. So then you won't be confused about what happened and you will know what to do to fix it.

Exceptions, on the other hand, i find it normal to be thrown only by the OS (or runtime) when something serious happens and your application would normally crash. Like division by zero. But not when a folder is not found, file cannot be opened and situations like these, which are normal to happen so are part of the usual workflow of your program.

I stumbled across this problem when i had to code in C# a while ago. 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. I simply expected it not to give me any results, but not crash because it threw an exception that i did not catch. 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. It's also sad that there are languages, like C#, that force this way to you :(

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.