Optional vs throwing an exception

前端 未结 3 1112
难免孤独
难免孤独 2021-02-12 09:34

Is it true that since Java 1.8 returning Optional object is more preferable than throwing an exception? Increasingly i see the code like this:

  p         


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-12 10:05

    In situations where errors might arise, a suitable datatype is Try.

    Instead of using the abstractions 'present' or 'empty', a Try uses the abstractions 'failure' or 'success'.

    As Try is not provided by Java 8 out of the box, it is necessary to use some 3. party library. (Maybe we will see it added in Java 9?)

    Try for Java

提交回复
热议问题