0
0
Javaprogramming~10 mins

Throw keyword in Java - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to throw an exception when the number is negative.

Java
if (number < 0) {
    [1] new IllegalArgumentException("Negative number not allowed");
}
Drag options to blanks, or click blank then click option'
Atry
Bthrows
Ccatch
Dthrow
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using 'throws' instead of 'throw' to throw an exception.
Trying to use 'catch' or 'try' to throw an exception.
2fill in blank
medium

Complete the method to throw a NullPointerException when input is null.

Java
public void checkInput(String input) {
    if (input == null) {
        [1] new NullPointerException("Input cannot be null");
    }
}
Drag options to blanks, or click blank then click option'
Athrows
Bthrow
Ctry
Dcatch
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using 'throws' inside the method body instead of 'throw'.
Trying to catch the exception instead of throwing it.
3fill in blank
hard

Fix the error in throwing a checked exception inside the method.

Java
public void readFile(String path) [1] {
    if (path == null) {
        throw new IOException("File path is null");
    }
}
Drag options to blanks, or click blank then click option'
Athrows IOException
Bthrow IOException
Cthrows IOException()
Dthrow IOException()
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using 'throw' in method signature instead of 'throws'.
Adding parentheses after IOException in the signature.
4fill in blank
hard

Fill both blanks to throw an ArithmeticException when dividing by zero.

Java
public int divide(int a, int b) [1] {
    if (b == 0) {
        [2] new ArithmeticException("Cannot divide by zero");
    }
    return a / b;
}
Drag options to blanks, or click blank then click option'
Athrows ArithmeticException
Bthrow
Cthrows IOException
Dthrow new
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using 'throw' in the method signature instead of 'throws'.
Using 'throw new' as a single option instead of splitting keywords.
5fill in blank
hard

Fill all three blanks to throw a custom exception when age is invalid.

Java
public void setAge(int age) [1] {
    if (age < 0 || age > 150) {
        [2] new [3]("Invalid age: " + age);
    }
}
Drag options to blanks, or click blank then click option'
Athrows InvalidAgeException
Bthrow
CInvalidAgeException
Dthrows Exception
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using 'throws Exception' instead of the specific custom exception.
Not using 'throw' keyword inside the method body.