Challenge: Exception Handling
Try to implement a class using proper exception messages for invalid input.
We'll cover the following
Task
You are given a User
class with the methods that set and get the user name and age.
- Add code to the
setName()
method that throws the exception“The name should be at least 3 characters long”
whenever the user’s name is shorter than 3 letters. - Add code to the
setAge()
method that throws the exception“The age cannot be zero or less”
whenever the user’s age is less than or equal to zero. - In the
test()
method, feed the class with this nested array:$dataForUsers = array( array("Ben",4), array("Eva",28), array("li",29), array("Catie","not yet born"), array("Sue",1.5) );
- Write a
foreach
loop (like the one we’ve already used in this chapter) that feeds the array to the class and handles the exceptions by echoing the custom error messages as well as the file path in which the exception was thrown.
Expected output
Ben is 4 years old. Eva is 28 years old. Error: The name should be at least 3 characters long in the file: /usercode/main.php. Error: The age cannot be zero or less in the file: /usercode/main.php. Sue is 1 years old.
Coding exercise
Since these problems are designed for your practice, try to solve them yourself first. If you get stuck, you can click the “Show Solution” button to see how the problem can be solved. Good luck!
Get hands-on with 1400+ tech skills courses.