Why not use exceptions as regular flow of control?

后端 未结 24 1816
心在旅途
心在旅途 2020-11-21 07:30

To avoid all standard-answers I could have Googled on, I will provide an example you all can attack at will.

C# and Java (and too many others) have with plenty of ty

24条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 07:56

    Typically there is nothing wrong, per se, with handling an exception at a low level. An exception IS a valid message that provides a lot of detail for why an operation cannot be performed. And if you can handle it, you ought to.

    In general if you know there is a high probability of failure that you can check for... you should do the check... i.e. if(obj != null) obj.method()

    In your case, i'm not familiar enough with the C# library to know if date time has an easy way to check whether a timestamp is out of bounds. If it does, just call if(.isvalid(ts)) otherwise your code is basically fine.

    So, basically it comes down to whichever way creates cleaner code... if the operation to guard against an expected exception is more complex than just handling the exception; than you have my permission to handle the exception instead of creating complex guards everywhere.

提交回复
热议问题