Difference between Unchecked exception or runtime exception

后端 未结 8 1537
忘了有多久
忘了有多久 2020-11-29 21:55

This was an interview question. What is the main difference between unchecked exception and error as both are not caught? They will terminate the program.

8条回答
  •  温柔的废话
    2020-11-29 22:09

    Checked Exception:

    • The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions.
    • Also known as compile time exception because these type of exceptions are checked at compile time. That means if we ignore these exception (not handled with try/catch or throw the exception) then a compilation error occurred.
    • They are programmatically recoverable problems which are caused by unexpected conditions outside control of code (e.g. database down, file I/O error, wrong input, etc)
    • We can avoid them using try/catch block.
    • Example: IOException, SQLException etc

    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.

提交回复
热议问题