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 exceptionnew 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
EasyCreate a method named validateAge that takes two arguments:
- An integer (
age) to validate - 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 exceptionnew 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());
}
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap