Using exception handlingQuestion: Discuss the advantages and disadvantages of exception handling in C# and contrast them with a primitive error-handling technique in which each called method returns an error code which must be tested by the caller. Answer: In a language that does not have exception handling, every method must return an error code, which can then be handled by the caller, for example: errCode = M1(...); if (errCode == 0) { errCode = M2(...); if (errCode == 0) { errCode = M3(...); if (errCode != 0) Error(...); } else Error(...); } else Error(...); In contrast to this example, exception handling has the following advantages:
A possible disadvantage of exception handling is that programming languages which support this mechanism become more complex and programs can become slightly larger (one must declare an exception class and write a try statement as well as one or more throw statements). In general, however, these minor problems are more than outweighed by the advantages of exception handling. Some people consider it a serious deficiency of C# that a method signature does not define the exceptions that can occur in this method (like in Java). From a software engineering point of view, such a specification would of course be desirable: (1) It shows which exceptions can occur when calling a method and (2) the compiler can make sure that the caller handles those exceptions. However, experience shows, that programmers are lazy and often react to the force of having to write catch clauses by writing empty catch clauses thinking that they will fill them out later, but of course forget to do so. An empty catch clause is worse than no catch clause, because it silently swallows exceptions. In C#, an unhandled exception leads at least to the abortion of the program so that the error is detected. |
||