Throws or try-catch

后端 未结 10 1300
别跟我提以往
别跟我提以往 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:42

    If you use a try catch, when the exception occurs, the remaining codes would be still executed.

    If you indicate the method to throw the exception, then when the exception occurs, the code would stop being executed right away.

    0 讨论(0)
  • 2020-11-28 03:45
    • catch an exception only if you can handle it in a meaningful way
    • declare throwing the exception upward if it is to be handled by the consumer of the current method
    • throw exceptions if they are caused by the input parameters (but these are more often unchecked)
    0 讨论(0)
  • 2020-11-28 03:49

    try-catch pair is used when you want to provide customise behaviour, in case if exception occurs.....in other words...you have a solution of your problem (exception occurrence) as per your programme requirements.....

    But throws is used when you don't have any specific solution regarding the exception occurrence case...you just don't want to get abnormal termination of your programme....

    Hope it is correct :-)

    0 讨论(0)
  • 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).
    0 讨论(0)
提交回复
热议问题