Throwing Exceptions in Java - Quiz Explanation

The correct answers are indicated below, along with text that explains the correct answers.
 
1. When would you throw an exception?
Please select the best answer.
  A. When you are checking the format of user input
  B. When you are anticipating a runtime error
  C. When you want to inform the calling routine of a problem
  The correct answer is C.
You should throw an exception when there's an error and you want to notify the caller.

2. What is wrong with the following snippet (assuming error is a Boolean)?
if (error) {
   throw NumberFormatException;
}

Please select the best answer.
  A. We never made a new instance of the exception class we want to throw.
  B. There is no such class as a NumberFormatException.
  C. The throw keyword cannot be used in this way.
  The correct answer is A.
To throw an exception in this way, you must write: throw new NumberFormatException(); |
The problem lies in the way the NumberFormatException is being thrown. In Java, exceptions need to be instantiated before being thrown. You cannot throw an exception class directly.
Here’s how to correct it:
if (error) {
   throw new NumberFormatException();
}

Explanation:
  1. new NumberFormatException(): In Java, exceptions are objects, so you need to create a new instance of the NumberFormatException class using the new keyword.
  2. Optional message: If you want to provide a message explaining why the exception occurred, you can pass a string as an argument to the exception's constructor, like this:
    if (error) {
      throw new NumberFormatException("Invalid number format detected");
    }
    

This will correctly throw the exception when error is true.

3. What is wrong with the following?
class Trouble {
   void rightHere() {
      throw new Exception();
   }
}

Please select the best answer.
  A. You cannot throw an instance of the Exception class.
  B. The throw keyword is not used correctly
  C. The method rightHere() is not defined correctly
  The answer is C.
A method that throws a checked exception must indicate that it throws this exception by using the throws keyword in its signature, as in: void rightHere throws Exception . . .