Java Interview Questions and Answers for Beginners - 2

Question: 6

What classes of exceptions may be throw statement?

A throw statement may throw any expression that may be assigned to the Throwable type.

Question: 7

What is the relationship between a method’s throw clause and the exceptions that can be thrown during the method’s execution?

A method’s throws clause must declare any checked exceptions that are not caught within the body of the method.

Question: 8

What is difference between throw and throws?

throw keyword throws keyword
throw is used to explicitly throw an exception. throws is used to declare an exception.
checked exceptions cannot be propagated with throw only. checked exception can be propagated with throws.
throw is followed by an instance. throws is followed by class.
throw is used within the method. throws is used with the method signature.
throw is used within the method. throws is used with the method is signature.
you cannot throw multiple exception. you can declare multiple exception.

 

Question: 9

What things should be kept in mind while creating your own exceptions in Java?

While creating your own exception.

All exceptions must be a child of Throwable.

If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.

You want to write a runtime exception, you need to extend the Run time Exception class.

Question: 10

When assertion should be avoided?

In following situations the assertions should be avoided.

When assertion becomes a performance issue. It means an assertion should not include too complex logic equaling implementation of a method.

Do not use assertions in argument checking of public methods. As argument checking is part of a method implementation and if these arguments are erroneous then it will throw runtime exception and assertion failure will not result in any error.

Related Questions