Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Exception Handling in OOP | Organizing and Applying OOP in PHP
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
Object-Oriented PHP

bookException Handling in OOP

Exception Handling in OOP

Exception handling is a key part of building robust PHP applications. An exception is a special object that signals something unexpected has happened during your program’s execution. In PHP, exceptions are used to manage errors in a controlled way, allowing you to respond to problems without crashing your entire application.

When you use object-oriented programming (OOP) in PHP, you often work with exceptions by throwing and catching them. This means you can detect when something goes wrong, handle it gracefully, and keep your code organized. PHP provides built-in support for exceptions through the Exception class, and you can create your own custom exception classes to handle specific situations.

Errors vs Exceptions

  • Errors: Usually indicate a problem in your code, such as syntax mistakes or calling an undefined function. They often stop the script immediately.
  • Exceptions: Represent exceptional situations that you can handle gracefully using try, catch, and finally. Exceptions can be thrown intentionally in your code using the throw keyword.

Code Example

Below, you will see an example of exception handling in PHP OOP, showing how to throw and catch exceptions within class methods. It demonstrates using try, catch, and finally to handle errors gracefully, ensuring your program can respond to unexpected situations without crashing.

exception_example.php

exception_example.php

copy
123456789101112131415161718192021222324252627282930313233343536
<?php class BankAccount { private $balance; public function __construct($initialBalance) { $this->balance = $initialBalance; } public function withdraw($amount) { if ($amount > $this->balance) { // Throw an exception if withdrawal amount is too high throw new Exception("Insufficient funds: Cannot withdraw $amount."); } $this->balance -= $amount; echo "Withdrawn: $amount. Remaining balance: $this->balance\n"; } public function deposit($amount) { $this->balance += $amount; echo "Deposited: $amount. New balance: $this->balance\n"; } } // Using the class with exception handling $account = new BankAccount(100); try { $account->withdraw(50); // Works fine $account->withdraw(100); // Will throw an exception } catch (Exception $e) { // Catch the exception and handle it echo "Error: " . $e->getMessage() . "\n"; } finally { // This block always runs echo "Transaction attempt finished.\n"; }

This example demonstrates exception handling in PHP OOP using the BankAccount class. The class has a private property $balance and methods withdraw() and deposit(). The withdraw() method throws an Exception if the requested amount is greater than the available balance.

In the main script, we create a BankAccount object $account with an initial balance of 100. Using a try block, we attempt to withdraw 50, which works, and then 100, which triggers the exception. The catch block catches the Exception object $e and prints its message, preventing the script from crashing. Finally, the finally block executes regardless of whether an exception occurred, showing that cleanup or final actions can always be performed. This setup makes the bank account operations safe and predictable.

question mark

What is an exception in PHP?

Select the correct answer

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 3. Chapitre 3

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

Suggested prompts:

Can you explain how to create a custom exception class in PHP?

What is the difference between using try-catch and just letting errors stop the script?

Can you show more real-world scenarios where exception handling is useful in PHP OOP?

bookException Handling in OOP

Glissez pour afficher le menu

Exception Handling in OOP

Exception handling is a key part of building robust PHP applications. An exception is a special object that signals something unexpected has happened during your program’s execution. In PHP, exceptions are used to manage errors in a controlled way, allowing you to respond to problems without crashing your entire application.

When you use object-oriented programming (OOP) in PHP, you often work with exceptions by throwing and catching them. This means you can detect when something goes wrong, handle it gracefully, and keep your code organized. PHP provides built-in support for exceptions through the Exception class, and you can create your own custom exception classes to handle specific situations.

Errors vs Exceptions

  • Errors: Usually indicate a problem in your code, such as syntax mistakes or calling an undefined function. They often stop the script immediately.
  • Exceptions: Represent exceptional situations that you can handle gracefully using try, catch, and finally. Exceptions can be thrown intentionally in your code using the throw keyword.

Code Example

Below, you will see an example of exception handling in PHP OOP, showing how to throw and catch exceptions within class methods. It demonstrates using try, catch, and finally to handle errors gracefully, ensuring your program can respond to unexpected situations without crashing.

exception_example.php

exception_example.php

copy
123456789101112131415161718192021222324252627282930313233343536
<?php class BankAccount { private $balance; public function __construct($initialBalance) { $this->balance = $initialBalance; } public function withdraw($amount) { if ($amount > $this->balance) { // Throw an exception if withdrawal amount is too high throw new Exception("Insufficient funds: Cannot withdraw $amount."); } $this->balance -= $amount; echo "Withdrawn: $amount. Remaining balance: $this->balance\n"; } public function deposit($amount) { $this->balance += $amount; echo "Deposited: $amount. New balance: $this->balance\n"; } } // Using the class with exception handling $account = new BankAccount(100); try { $account->withdraw(50); // Works fine $account->withdraw(100); // Will throw an exception } catch (Exception $e) { // Catch the exception and handle it echo "Error: " . $e->getMessage() . "\n"; } finally { // This block always runs echo "Transaction attempt finished.\n"; }

This example demonstrates exception handling in PHP OOP using the BankAccount class. The class has a private property $balance and methods withdraw() and deposit(). The withdraw() method throws an Exception if the requested amount is greater than the available balance.

In the main script, we create a BankAccount object $account with an initial balance of 100. Using a try block, we attempt to withdraw 50, which works, and then 100, which triggers the exception. The catch block catches the Exception object $e and prints its message, preventing the script from crashing. Finally, the finally block executes regardless of whether an exception occurred, showing that cleanup or final actions can always be performed. This setup makes the bank account operations safe and predictable.

question mark

What is an exception in PHP?

Select the correct answer

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 3. Chapitre 3
some-alt