difference between errors and unchecked exceptions in java?

后端 未结 7 1110
时光取名叫无心
时光取名叫无心 2020-12-16 18:22

As we know if any error or any unchecked exception occurs then our program will halt, then what are the differences between those?

7条回答
  •  情书的邮戳
    2020-12-16 18:46

    Unchecked Exception:

    • The classes that extend RuntimeException are known as unchecked exceptions
    • Unchecked exceptions are not checked at compile-time rather they are checked at runtime.And thats why they are also called "Runtime Exception"
    • They are also programmatically recoverable problems but unlike checked exception they are caused by faults in code flow or configuration.
    • Example: ArithmeticException,NullPointerException, ArrayIndexOutOfBoundsException etc
    • Since they are programming error, they can be avoided by nicely/wisely coding. For example "dividing by zero" occurs ArithmeticEceeption. We can avoid them by a simple if condition - if(divisor!=0). Similarly we can avoid NullPointerException by simply checking the references - if(object!=null) or using even better techniques

    Error:

    • Error refers irrecoverable situation that are not being handled by try/catch

    • Example: OutOfMemoryError, VirtualMachineError, AssertionError etc.

      This question may also be helpful in this context - Runtime/Checked/Unchecked/Error-Exception

提交回复
热议问题