Why is exception handling bad?

前端 未结 15 1409
温柔的废话
温柔的废话 2020-12-04 05:46

Google\'s Go language has no exceptions as a design choice, and Linus of Linux fame has called exceptions crap. Why?

15条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 06:08

    A great use-case for exceptions is thus....

    Say you are on a project and every controller (around 20 different major ones) extends a single superclass controller with an action method. Then every controller does a bunch of stuff different from each other calling objects B, C, D in one case and F, G, D in another case. Exceptions come to the rescue here in many cases where there was tons of return code and EVERY controller was handling it differently. I whacked all that code, threw the proper exception from "D", caught it in the superclass controller action method and now all our controllers are consistent. Previously D was returning null for MULTIPLE different error cases that we want to tell the end-user about but couldn't and I didn't want to turn the StreamResponse into a nasty ErrorOrStreamResponse object (mixing a data structure with errors in my opinion is a bad smell and I see lots of code return a "Stream" or other type of entity with error info embedded in it(it should really be the function returns the success structure OR the error structure which I can do with exceptions vs. return codes)....though the C# way of multiple responses is something I might consider sometimes though in many cases, the exception can skip a whole lot of layers(layers that I don't need to clean up resources on either).

    yes, we have to worry about each level and any resource cleanup/leaks but in general none of our controllers had any resources to clean up after.

    thank god we had exceptions or I would have been in for a huge refactor and wasted too much time on something that should be a simple programming problem.

提交回复
热议问题