Câu hỏi phỏng vấn PHP
Câu hỏi

Explain how we handle exceptions in PHP?

Câu trả lời

Here is how to handle exceptions in PHP:

Exception Handling in PHP

Exception handling in PHP allows you to gracefully handle errors and unexpected situations in your code. When an exception occurs, the normal flow of execution is interrupted, and the code jumps to the exception handling block. This allows you to handle the exception, log it, or display a user-friendly error message.

Try-Catch Block

The main way to handle exceptions in PHP is using a try-catch block. Here's how it works:

  1. The code that might throw an exception is placed inside the try block.
  2. One or more catch blocks follow the try block to handle specific types of exceptions.
  3. If an exception is thrown inside the try block, the code jumps to the matching catch block based on the exception type.

Here's an example:

php Copy
try {
    // Code that might throw an exception
    $result = 10 / 0; // Throws a DivisionByZeroError
} catch (DivisionByZeroError $e) {
    // Handle the exception
    echo "Error: " . $e->getMessage();
}

In this example, if a DivisionByZeroError is thrown inside the try block, the code jumps to the catch block, and the error message is displayed.

Throwing Exceptions

You can also throw your own exceptions using the throw keyword. This is useful when you want to signal an exceptional condition in your code. When you throw an exception, you can specify the type of exception and provide a custom message.

php Copy
if ($age < 18) {
    throw new Exception("You must be at least 18 years old.");
}

Exception Types

PHP has a built-in hierarchy of exception classes. The base class is Exception, and more specific exception types in...

junior

junior

Gợi ý câu hỏi phỏng vấn

middle

What is the difference between using self and $this ?

junior

What are the main differences between const vs define

junior

Is there a difference between isset and !empty ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào