Throws or try-catch

后端 未结 10 1362
别跟我提以往
别跟我提以往 2020-11-28 03:15

What is the general rule of thumb when deciding whether to add a throws clause to a method or using a try-catch?

From what I\'ve read mysel

10条回答
  •  爱一瞬间的悲伤
    2020-11-28 03:52

    In general, a method should throw an exception to its caller when it can't handle the associated problem locally. E.g. if the method is supposed to read from a file with the given path, IOExceptions can't be handled locally in a sensible way. Same applies for invalid input, adding that my personal choice would be to throw an unchecked exception like IllegalArgumentException in this case.

    And it should catch an exception from a called method it if:

    • it is something that can be handled locally (e.g. trying to convert an input string to a number, and if the conversion fails, it is entirely valid to return a default value instead),
    • or it should not be thrown (e.g. if the exception is coming from an implementation-specific lower layer, whose implementation details should not be visible to the caller — for example I don't want to show that my DAO uses Hibernate for persisting my entities, so I catch all HibernateExceptions locally and convert them into my own exception types).

提交回复
热议问题