What is the difference between the "throw" and "throws" keywords Interview Question?

First, we need to see what is Check and Uncheck Exception in Java some examples of Checked Exception and Unchecked Exceptions in Java.

Unchecked exceptions:- All classes which extend RuntimeException are called Unchecked exceptions. They are like programming bugs, such as logic Errors or Improper Code.
"throw" and "throws" keywords Interview Question
"throw" and "throws"

Unchecked exceptions are:
  • NullPointerException
  • IllegalArgumentException 
  • ClassCastException
  • ArithmeticException
  • IndexOutOfBoundsException

Checked exceptions: Checked exceptions in Java extend the Exception class but do not extend RuntimeException class. Checked exceptions are like method body code may throws some Exception you must either handle this Exception or specify that it may throws this Exception.

Checked exceptions are:
  • SQLException
  • FileNotFoundException
  • IOException
Now the main difference between throw and throws is like Java supports two keywords throw and throws for exception type here is some small difference between throw and throws.

Throw Throws
Throw Keyword is used to throw an Exception Explicitly. It Can throw only one Exception at a time. Throws keyword is used to declare multiple Exception, separate by Comma
Throw Keyword is used inside a Function Throws are used with the method Signature.
Throw Keyword used and instance of Exception to be thrown. Throws keyword used class name of Exception to be Thrown.
throw new MyException();
throws IOException.

Post a Comment

Previous Post Next Post