can't java unchecked exceptions be handled using try/catch block?

后端 未结 8 1879
旧时难觅i
旧时难觅i 2020-12-24 02:29

In a tutorial I found that Unchecked Exception can\'t be handled by your code i.e. we can\'t use try/catch block and the examples are exception

相关标签:
8条回答
  • 2020-12-24 03:16

    The only difference between checked and unchecked exceptions is that checked ones have to be either caught or declared in the method signature using throws, whereas with unchecked ones this is optional.

    Unchecked Exception can't be handled by your code i.e. we can't use try/catch block

    Sure we can - but we don't have to.

    Also i think throw keyword can be used only with try/catch block.can throw Keyword be used with Unchecked Exception?

    Note that there are two keywords:

    • throw explicitly throws an exception object you created. throw new NullPointerException(); works perfectly fine, though explicitly creating that particular exception is uncommon and most would consider it bad style.
    • throws declares that a method may throw that exception. With unchecked exceptions this is optional, but can be useful to document the fact (again, one would normally not declared throws NullPointerException because that is pretty much a given).
    0 讨论(0)
  • 2020-12-24 03:17

    In addition to Guillaume:

    • unchecked exceptions are usually programming errors, which should not happen at all if implemented correctly (index out of bound, null pointer, class cast,...) and therefore the caller/ user usually cannot do anything about them.
    • checked exceptions are thrown because it was outside of the control of the programmer (network not availabe, filesystem not available, concurrent modifications such as duplicated primary key,...)
    • errors are usually thrown by the JVM and the application usually has to stop (out of memory, stack overflow,...)
    0 讨论(0)
提交回复
热议问题