Menu
Coddy logo textTech

Throwing Exceptions

Part of the Logic & Flow section of Coddy's Java journey — lesson 42 of 59.

The throw keyword in Java allows you to explicitly throw an exception. Here's the basic structure:

throw new ExceptionType("Error message");

The components are:

  • throw: Keyword to throw an exception
  • new ExceptionType: Creates a new exception (like IllegalArgumentException)
  • "Error message": Describes what went wrong

Let's see it in action:

int age = -5;
if (age < 0) {
    throw new IllegalArgumentException("Age cannot be negative");
}

After executing the above code, the program throws:

IllegalArgumentException: Age cannot be negative

challenge icon

Challenge

Easy

Create a method named validateAge that takes two arguments:

  1. An integer (age) to validate
  2. A boolean (strict) that determines validation rules

The method should throw exceptions based on these rules:

  • If age is negative: throw IllegalArgumentException with message "Age cannot be negative"
  • If age is above 150: throw IllegalArgumentException with message "Age cannot be greater than 150"
  • If strict is true and age is 0: throw IllegalArgumentException with message "Age cannot be zero in strict mode"
  • If no exception is thrown: return age as a string

Cheat sheet

The throw keyword allows you to explicitly throw an exception:

throw new ExceptionType("Error message");

Components:

  • throw: Keyword to throw an exception
  • new ExceptionType: Creates a new exception (like IllegalArgumentException)
  • "Error message": Describes what went wrong

Example:

int age = -5;
if (age < 0) {
    throw new IllegalArgumentException("Age cannot be negative");
}

Try it yourself

import java.util.Scanner;

public class Main {
    public static String validateAge(int age, boolean strict) {
        // Write your code here
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int age = Integer.parseInt(scanner.nextLine());
        boolean strict = Boolean.parseBoolean(scanner.nextLine());
        
        try {
            System.out.println(validateAge(age, strict));
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow