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

  1. throw new ExceptionType(message)
  2. Check condition before throwing
  3. Catch in same or calling method

Related Exception Handling exercises

Practice all Exception Handling exercises · Run this idea in the Java compiler