What are the two types of Exceptions in Java ? Which are the differences between them ?

  • Java has two types of exceptions: checked exceptions and unchecked exceptions.
  • The difference between checked and unchecked exceptions are:
    • Checked exceptions (IOException, FileNotFoundException) are checked at compile-time. It means if a method is throwing a checked exception then it should handle the exception using try-catch block or it should declare the exception using throws keyword, otherwise the program will give a compilation error. It is named as checked exception because these exceptions are checked at Compile time.
    • Unchecked exceptions (All Unchecked exceptions are direct sub classes of RuntimeException class e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException) are not checked at compile time. It means if your program is throwing an unchecked exception and even if you didn’t handle/declare that exception, the program won’t give a compilation error. Most of the times these exception occurs due to the bad data provided by user
  • Checked and unchecked exceptions in java with examples

What is the difference between Exception and Error in java ?

  • An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error.
  • Exceptions are conditions that occur because of bad input or human error etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.)

What is the difference between throw and throws ?

  • Throws clause in used to declare an exception and thow keyword is used to throw an exception explicitly.
  • throw is followed by an instance variable and throws is followed by exception class names.
  • The keyword throw is used inside method body to invoke an exception and throws clause is used in method declaration (signature).