PHP Try-Catch Blocks 🎯

beginner
14 min

PHP Try-Catch Blocks 🎯

Welcome back, aspiring coder! Today, we're going to delve into one of the most important error-handling mechanisms in PHP - Try-Catch Blocks. Let's get started! πŸ“

Understanding Try-Catch Blocks πŸ’‘

In PHP, Try-Catch blocks help us handle exceptions that might occur during the execution of our code. They provide a structured way to deal with errors and make our code more robust.

php
try { // code to be executed } catch (ExceptionType $exception) { // code to handle the exception }

πŸ“ Note: The try block contains the code we want to protect from exceptions. The catch block contains the code that will be executed when an exception occurs in the try block.

Exception Types πŸ’‘

PHP has several built-in exception types that we can use. Here are some of the most common ones:

  • Exception: This is the base class for all exceptions in PHP. It's rarely used directly.
  • LogicException: Thrown for logical errors in the code, such as an invalid argument.
  • RuntimeException: Thrown for runtime errors, like trying to access an undefined index in an array.
  • ErrorException: Thrown for PHP run-time errors, such as notices, warnings, and fatal errors.

Creating Custom Exceptions πŸ’‘

You can also create your own custom exceptions. Here's an example:

php
class CustomException extends Exception { // custom exception code here }

Now, you can throw this custom exception using the throw keyword:

php
try { throw new CustomException("A custom exception occurred!"); } catch (CustomException $e) { echo $e->getMessage(); }

Try-Catch Block Examples πŸ’‘

Example 1: Handling Divide By Zero Error

php
try { $result = 10 / 0; echo $result; } catch (DivisionByZeroError $e) { echo "Error: Division by zero is not allowed."; }

Example 2: Handling Custom Exception

php
class CustomException extends Exception { // custom exception code here } try { throw new CustomException("A custom exception occurred!"); } catch (CustomException $e) { echo $e->getMessage(); }

Quiz 🎯

Quick Quiz
Question 1 of 1

What is the base class for all exceptions in PHP?

Quick Quiz
Question 1 of 1

What is the purpose of the `try` block in PHP?

That's it for today! With this lesson, you've taken a step closer to mastering PHP error handling. Keep coding and learning! πŸ’‘