I am currently studying C # using Schildt’s textbook, and he teaches to conclude all narrow moments in a try - catch .

Is this normal code branching practice, or is it better to use if - else ? I, of course, understand the difference between errors and exceptions. But now my border is blurred between some exceptions and ordinary branches in the code.

For example, the operation of dividing one number by another implies that the user can (try) divide the number by zero. On the one hand, the result of this operation will be an exception that can be processed. On the other hand, it is possible and not to bring the case to the exception by checking the input numbers in advance.

How to act in the community of professional programmers?

  • 3
    For starters, don't read Schildt. He is known for the terrible quality of books and disgusting advice. Read better Albahari. - VladD
  • 2

3 answers 3

In general, the substitution of exceptions by conditional blocks is not the most sensible idea. Any function (method) should, in principle, perform one task assigned to it. If for one reason or another the task cannot be completed, an exception should be thrown. The method itself in the general case should not be engaged in handling its own exceptions, for this there is the code calling it. The method must either complete the task or report the impossibility of completing it. Let's go back to your example:

For example, the operation of dividing one number by another implies that the user can (try) divide the number by zero. On the one hand, the result of this operation will be an exception that can be processed. On the other hand, it is possible and not to bring the case to the exception by checking the input numbers in advance.

In this case, an exception must be caused - your method received incorrect input data, and cannot correctly perform a division operation. Here your phrase is interesting:

On the other hand, it is possible and not to bring the case to the exception by checking the input numbers in advance.

Can. But what should the code do next if the check fails? Return some magic value of type -1 or 0? It will be incorrect from the point of view of logic. Show error message? This will smack of a design error - a completely different code must be responsible for displaying error messages. Code connectivity will appear, and this is very bad.

In addition, there are such exceptional situations in which no if-else will help. Say, could not open the database connection. What should the program do next? Enter the condition and try again to open it, and then another, another and another? Hardly.

As for the if-else, it makes sense to use them where the “failed” option is just one of the possible correct program states.

To summarize, the method must either complete the task or report the impossibility of its execution. Handling your own exceptions is often not necessary. Should forward them up.

I highly recommend reading Richter’s chapter on exceptions. And indeed this book itself

  • I looked at the table of contents of the book, and it seemed to me that it is for those who already understand C #? What kind of LVL up? - teanYCH
  • Well, in general, yes, it is not for the initial study of the language - DreamChild
  • Clear. Then I’ll finish reading Shildt, and then proceed to Richter. I already had some idea of ​​how NOT to program, so the Future programmer’s Shield in me cannot be killed, no matter how hard he tries :) - teanYCH
  • @teanYCH the words that you can’t learn by Shildt were not said by me) - DreamChild
  • one
    Yes, I was just trying to give a joke of humor. All textbooks differ on opinions. Someone likes the author, someone does not like. - teanYCH

No, I do not agree with Shieldt.

Typically, the code is structured in such a way that:

  • Most operations have the right to throw an exception. They do not catch exceptions to the called code, except in rare cases where it is really needed.
  • If you are manually managing resources, try / finally rather than try / catch is most likely useful.
  • try / catch wraps as large, external blocks of program logic as possible. For example, the iteration of the main loop.

About where to use exceptions, and where if / else: if the operation can be expected to fail, use branching. If the operation fails only in exceptional cases, use exceptions.

Example: if a user entered text in the editbox, you cannot assume that he entered a number. Use this code:

 if (int.TryParse(s, out value)) return value; else // покажите message box и не закрывайте диалог 

If the value is read from the configuration file, a non-numeric value where a number is expected is a serious problem, and the code changes accordingly:

 return int.Parse(s); // если там не число, бросаем исключение, которое // будет поймано на верхнем уровне операцией чтения конфигурации 

Additional reading: http://www.artima.com/intv/handcuffs.html

  • In my head, quite a while in the background, the question is spinning (in principle, I would draw a separate question, but it is even more important to search Google). So - are you throwing out exceptions from wcf-services or returning something like OperationResult <T>? - Veikedo
  • @Veikedo: I did not write WCF services myself, so I cannot say. But if it is possible to throw an exception there, I would have done so. - VladD

Branching is the normal behavior of a program. Exceptions indicate a potential deformation of the logical integrity of a certain model, from which it must be saved (close connections, stop working with an object, etc.).

Here in C ++, as you said, exceptions are added as an auxiliary, non-mandatory mechanism. But try-catch is often much better readable than ingenious control over the validity of an object by many criteria, special variables.

  • one
    As a colleague has already indicated, branching is a normal program behavior. Exceptions = program errors. I would like to add that it is very difficult to consider all the options for branching. The try-catch mechanism can catch unaccounted options. In addition, this mechanism makes it possible to use the finally {} construct, which, despite the exception, will execute the necessary piece of code in any case. (for example, it will close the connection to the database) PS 2Free_ze - your nickname is interesting))) - Freezze
  • one
    @Freezze, "Exceptions = program errors". It is a pity that you think so. habrahabr.ru/post/130597 - teanYCH
  • "But try-catch is often better read." I think so too. After all, sometimes, in order not to hang the code with pasta checks for all sorts of values, it is easier to conclude everything in try-catch. - teanYCH
  • @teanYCH In its original form of an exception, these are errors. Erroneous situations at the level of program logic , rather than technical ones, such as dividing by zero, stack overflow, going beyond the buffer, etc. (although C # also likes sharing instances of special types on their occasion). Although no one forbids the use of exceptions for branching, but I read somewhere that the performance is sinking from the large number of exceptions being processed. @Freezze And hello to you, long lost Internet brother =) - free_ze
  • @ teanYCH I didn’t really put it right, I agree. Exceptions are not errors. Exceptions include errors. So it will be more true. - Freezze