0
0
PHPprogramming~30 mins

Custom exception classes in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom Exception Classes in PHP
📖 Scenario: Imagine you are building a simple banking system. You want to handle errors like withdrawing too much money or depositing invalid amounts in a clear way.
🎯 Goal: You will create custom exception classes to handle specific banking errors and use them in your code to show meaningful error messages.
📋 What You'll Learn
Create a custom exception class called InsufficientFundsException
Create a custom exception class called InvalidDepositException
Write a function withdraw that throws InsufficientFundsException if withdrawal amount is more than balance
Write a function deposit that throws InvalidDepositException if deposit amount is less than or equal to zero
Use try and catch blocks to handle these exceptions and print error messages
💡 Why This Matters
🌍 Real World
Custom exceptions help you handle specific errors in your programs clearly, like banking errors or user input mistakes.
💼 Career
Understanding custom exceptions is important for writing robust, maintainable code in professional software development.
Progress0 / 4 steps
1
Create the initial balance variable
Create a variable called $balance and set it to 1000.
PHP
Need a hint?

Use $balance = 1000; to set the starting balance.

2
Create custom exception classes
Create two custom exception classes called InsufficientFundsException and InvalidDepositException that both extend the built-in Exception class.
PHP
Need a hint?

Use class ClassName extends Exception {} to create custom exceptions.

3
Write withdraw and deposit functions with exceptions
Write a function called withdraw that takes $amount and throws InsufficientFundsException if $amount is greater than $balance. Write a function called deposit that takes $amount and throws InvalidDepositException if $amount is less than or equal to zero. Both functions should update the global $balance variable accordingly.
PHP
Need a hint?

Use throw new ExceptionName("message") inside the functions to raise errors.

4
Use try-catch blocks to handle exceptions and print results
Use try and catch blocks to call withdraw(1500) and deposit(-100). Catch InsufficientFundsException and InvalidDepositException separately and print their messages. Then print the final $balance.
PHP
Need a hint?

Use separate try blocks for each function call and catch the specific exceptions to print their messages.