Complete the code to throw an exception when the number is negative.
if (number < 0) { [1] new IllegalArgumentException("Negative number not allowed"); }
The throw keyword is used to actually throw an exception object in Java.
Complete the method to throw a NullPointerException when input is null.
public void checkInput(String input) {
if (input == null) {
[1] new NullPointerException("Input cannot be null");
}
}The throw keyword is used to throw an exception instance inside the method.
Fix the error in throwing a checked exception inside the method.
public void readFile(String path) [1] { if (path == null) { throw new IOException("File path is null"); } }
Checked exceptions like IOException must be declared in the method signature using throws.
Fill both blanks to throw an ArithmeticException when dividing by zero.
public int divide(int a, int b) [1] { if (b == 0) { [2] new ArithmeticException("Cannot divide by zero"); } return a / b; }
The method declares throws ArithmeticException and inside the method, use throw to throw the exception.
Fill all three blanks to throw a custom exception when age is invalid.
public void setAge(int age) [1] { if (age < 0 || age > 150) { [2] new [3]("Invalid age: " + age); } }
The method declares it throws InvalidAgeException, inside it uses throw to throw a new InvalidAgeException object.