Throwing Exceptions in Java: Explanation & Practice
Manually throw an exception
Problem summary
Throw an IllegalArgumentException if age is negative.
Starter code
public class Main {
public static void main(String[] args) {
int age = -5;
// Check age and throw exception if negative
// Catch and print error message
}
}Expected output and test cases
- Throw and catch
Error: Age cannot be negative
Hints
- throw new ExceptionType(message)
- Check condition before throwing
- Catch in same or calling method
Related Exception Handling exercises
- Practice Multiple Catch Blocks in Java
- Practice Using Finally Block in Java
- Practice Using Throws Clause in Java
Practice all Exception Handling exercises · Run this idea in the Java compiler