3 ms·
Having programmed extensively in Java, C# and C++ I can say with confidence that checked exceptions is the most important thing missing in C++ and C#. Around th
by petilon 8y ago
Having programmed extensively in Java, C# and C++ I can say with confidence that checked exceptions is the most important thing missing in C++ and C#. Around the time C# was released there was a lot of debate around the topic of checked vs unchecked exceptions and this created an impression that Java's use of checked exceptions was "controversial". In fact it is a feature every modern language should have.
Exceptions that can be thrown by a method should be part of the contract of that method. Changing the list of the list of exceptions that can be thrown by a method is just like changing the parameters of the method. This is something that should cause calling code to fail to compile. This will allow you to inspect the calling code and decode how to deal with the new exception.
When the exception that can be thrown by a method is not known you don't know what exceptions to catch and what exceptions to pass through to callers. You can't rely on documentation because the documentation is not verified be the compiler and so is not reliable. All you can do is to run the program a few times, see what exceptions you get and handle them. Even if you are able to determine the full list of exceptions using this strategy, a future revision of the called method can throw a new exception and cause your program to crash. As a result, in large C# code bases it is common to see catching the base Exception class because this is the only way to prevent a crash. This causes exceptions to be "swallowed" because higher level code that is actually prepared to handle certain exceptions never get the exception.
With Java this problem doesn't exist. When you call a function you know exactly what exceptions can be thrown and you can catch (or pass through) exactly those exceptions. There is no need to catch the base exception class.