This project demonstrates how to manually throw exceptions in Java using the throw keyword. It ensures that game scores remain positive by triggering an IllegalArgumentException when an invalid value is processed.
- Task: Implement
displayPositiveScore(int currentScore)with input validation. - Validation: Throw
IllegalArgumentExceptionifcurrentScoreis 0 or negative. - Message: "Cannot display negative score! The number is negative."
- Mechanism: Handle the exception in
mainusingtry-catch. - Goal: Maintain data integrity and provide clear feedback.
- Java 8+
If the condition currentScore < 0 is met, the program explicitly throws a new IllegalArgumentException. The main method catches the error and prints the exception's message to the console.
Current score: 50
Error: Cannot display negative score! The number is negative.
Project Structure:
src/com/yurii/pavlenko/
└── Solution.java
Code
package com.yurii.pavlenko;
public class Solution {
public static void displayPositiveScore(int currentScore) {
if (currentScore < 0) {
throw new IllegalArgumentException("Cannot display negative score! The number is negative.");
}
System.out.println("Current score: " + currentScore);
}
public static void main(String[] args) {
displayPositiveScore(50);
try {
displayPositiveScore(-5);
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
}This project is licensed under the MIT License.
Copyright (c) 2026 Yurii Pavlenko
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files...
License: MIT