Java Interview Questions


Q:

What are Checked and Unchecked Exceptions?

 
A: A checked exception is a subclass of Exception, excluding class RuntimeException and its subclasses. Making an exception checked forces client programmes to deal with the exception that may be thrown. Checked exceptions must be caught at compile time. Example: IOException.

Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. Example: ArrayIndexOutOfBoundsException.
.

Q:

Does the order of placing catch statements matter in the catch block?

 
A: Yes, it does. The FileNoFoundException is inherited from the IOException. So FileNoFoundException is caught before IOException. Exception’s subclasses have to be caught first before the General Exception
.
Q:

What is the difference between throw and throws keywords?

 
A: The throw keyword denotes a statement that causes an exception to be initiated. It takes the Exception object to be thrown as an argument. The exception will be caught by an enclosing try-catch block or propagated further up the calling hierarchy. The throws keyword is a modifier of a method that denotes that an exception may be thrown by the method. An exception can be rethrown.
.
Q:

Explain the user defined Exceptions

 
A: User defined Exceptions are custom Exception classes defined by the user for specific purpose. A user defined exception can be created by simply sub-classing an Exception class or a subclass of an Exception class. This allows custom exceptions to be generated (using throw clause) and caught in the same way as normal exceptions.

Example:

class CustomException extends Exception { }
.


Java Interview Questions