What's better/faster? Try-catch or avoid exception?

前端 未结 8 784
花落未央
花落未央 2021-01-08 01:32

I would like to know, what\'s better or/and faster in general programming? Avoid the exception or wait for the exception?

Avoid the exception would be:



        
8条回答
  •  执笔经年
    2021-01-08 02:00

    Throwing exceptions is an expensive task, so I would always try and validate rather than catch.

    This should be easy enough to test, generate some code that throws an exception through each run and test it against a similar set of code that does conditional checking and measure the performance.

    If the code is documented with details of which conditions exceptions will be thrown, you should be able to adapt your calling code. Of course you can't handle every scenario (lower level runtime errors perhaps?), so your code should only really try and handle exceptions where it can actually react and possibly continue.

提交回复
热议问题