Is it possible to replace the if-else block with a try-catch block as follows?

String updateScriptPath = compileUpdateScript(inputVersion, searchPath); if (updateScriptPath == null) { Console.WriteLine(" No update sripts found :( "); } else { Console.WriteLine(updateScriptPath); } String updateScriptPath = compileUpdateScript(inputVersion, searchPath); try { Console.WriteLine(updateScriptPath); } catch { Console.WriteLine(" No scripts found :( "); } 
  • 2
    - No, it does not. - Igor
  • and what, when submitting null to Console.WriteLine an exception occurs? - Igor
  • try catch - for exceptions, your second example is null check through try-catch as something off topic - Ruslan_K

2 answers 2

You can, but:

  • First, the behavior will not be exactly the same. When calling Console.WriteLine() with null , an empty line will be displayed as a parameter. Those. c if only one line is always printed, and in the case of try/catch two lines can be displayed.
  • Secondly, even if calling Console.WriteLine() with null as a parameter resulted in an exception, use try/catch for checks — a bad tone. If it is possible to make a check in advance, you should always do it in advance. Read more about the correct use of try/catch here . As well as the subtleties of using and comparing c if discussed here and here .
  • “To use try / catch for checks is bad form” - since when and in what society? - ixSci
  • @ixSci ok, maybe I exaggerated it :). But if there is an opportunity to make a check, it is better to make a check. I would be glad to counterexamples. - andreycha
  • You know, I honestly can not think of an example where such a mixture is possible at all. Of course, if null can be returned from a function, then it should be checked, and not wait for a null exception. It's just that the case in question is somewhere on the edge of a clinical one, so it makes no sense to discuss it at all, as it seems to me. I’m a little bit about something else: for example, Parse / TryParse - the choice of one or another option is far from obvious and, depending on the task and preferences, any of them can be chosen. Those. there is no right way, so there is no “bad taste” - ixSci

It is impossible, try in your case refers to an attempt to output to the Console , and not to the results of compileUpdateScript .