Home >Backend Development >PHP Tutorial >PHP Master | Exceptional Exceptions
Core points
Exception
is equivalent to saying there is a "problem" and the code has no idea what is going on. Instead, a custom exception should always be thrown to inform the call code of the current situation, thereby providing fine-grained control over what is happening. PHP 5 introduces an exception handling mechanism, a special class that can be thrown and caught (as opposed to thrown errors) to indicate unexpected events. Unlike errors, exceptions are intended to be processed by the calling code and bubble upward along the execution chain until they are caught. Once an exception is thrown, the code in the current scope will stop executing (so, no line after the throw
statement will be executed), and control will be returned to the first matching exception handler (capturing block, configured Exception handler or exception handler provided by the language). Code execution continues from there only when the exception is caught. This article is not intended to explain exceptions at the entry level, but to provide some advice on how to better use exceptions. If you have never used exceptions before, you may need to consult the PHP manual or read the book "PHP Master: Writing Cutting-edge Code" written by my friends, which excellently explains the need for writing modern, reasonable PHP code All knowledge of
Error is not an exception
You may have learned about exceptions, but you may be wondering about the difference between a PHP error and a (custom) exception. The logic is actually very simple: the error is irrecoverable, occurs in the main execution loop, and indicates the stability of the environment. For example, if you try to access the scalar value as an array and raise E_NOTICE
, it means there is a problem with your code. There is no guarantee that continuing execution is safe. This condition cannot be corrected during execution. If the T_IF
is triggered by an unexpected E_PARSE
discovered by the parser, you will understand how this affects the stability of things. On the other hand, exceptions are recoverable, can (and usually) occur outside the main execution loop and do not indicate the stability of the system. It is a component that says, "I can't complete your request with the given input, so you can handle that information at will." If the library throws LengthException
, it means the passed value is too long or too short, so it can't Complete the given instruction with the current value. This doesn't mean your environment is unstable, it just means that your code has to adjust the length of the value by padding or truncating. Your code can catch this exception, update the value, and try again.
Not all exceptions are exceptions
This is one of the hardest questions to answer: What exactly does an exception need to be thrown? Of course, your exception must comply with three rules in the previous paragraph. Throwing exceptions when encountering corrupted memory is a very bad practice. Your code should throw an error instead so that PHP can abort as soon as possible, because the environment proves unsafe to continue execution. However, even if errors are unnecessary, no exception is required for all non-successful situations. That is to say: not all unsuccessful situations are exceptions. The word "abnormal" refers to an action that is not a normal operation or standard, and an abnormality that deviates from normal and expected situations. A former colleague once told me at dinner that the XML/RPC service their company uses is designed, the backbone of all public-facing operations. The architect then learned about exceptions and their convenience in indicating non-successful states. This pillar provides single sign-on functionality in addition to other features. Instead of accessing the database directly, the web application querys the XML/RPC service, which then responds based on the centralized data store that serves all web applications. When valid credentials are provided, a successful status will be returned. When a problem occurs, an exception is thrown and a message is displayed indicating the reason for the failure. Easy to capture, you can display the message to the user with a striking, shiny error message. But is the user providing an incorrect username and/or password really deviating from expectations? In my project, the users I handle are not perfect, they will typo or forget things. Getting incorrect credentials is very common, even more common than valid credentials. Verification credentials are the expected behavior of logging in to the system, so in this case, the XML/RPC service should return a status indicating whether the verification is successful or not. Although the credentials fail, the verification process itself is still successfully executed. If the verification process is not executed correctly, there are other problems. Maybe the data store is inaccessible, or something else. It is very uncommon for login systems to be unable to connect to their datastore because it cannot run without datastores. Therefore, this requires throwing an exception. Note: Some people may argue that the login system fails to connect to the data store is a sign that the environment is unstable and should therefore raise an error. However, logging in to the system is not responsible for raising an error for the data storage. Conversely, if the data storage connector/wrapper deems necessary, an error should be raised. Generally speaking, you can think of exceptions as situations where developers have to step in, view, and handle them. The code that occurs with the exception scenario cannot do this by itself. This is probably the developer has looked at the code and the way they handle it is to let it happen when it happens. Don't start emailing all exceptions to the network operations center; they won't be grateful! Handles what you can and should handle and the exception is thrown only if it really can't continue execution.
"Problem"
A few years ago, while I was hiking through Europe, I stumbled upon an unforgettable sight at a train station in Greece. One of the locker areas looked like a bomb exploded, with doors scattered on the ground, half hanging on hinges, or smashed. I later learned that they were removing the locker area, but it is worth noting how they communicated to the client that this area has been deactivated. There was a lot of tape on the center part, with a piece of paper pasting it with the words "problem". Technically, this is completely correct. There was obviously something wrong with the locker and the situation was handled by communicating it to the customer. You might find it interesting, but in fact you see this often in your code. If you just throw Exception
, you're basically saying "problem" and the code has no idea what's going on. Although Exception
is the base class for each exception, you can extend it with your own type. A wider collection of exceptions can be found in the SPL library, but this is far from the limit. Looking at major PHP frameworks like Zend Framework or Symfony, you'll find that they use custom exceptions for almost every different situation. It's a little cumbersome to write all these files so they can be loaded dynamically and maintain all the different types, but this provides fine-grained control over what happens for the framework and the consumers of that framework. If you only throw Exception
, then you can only be sure that something is wrong and you might as well give up. This means that you use exceptions the way they are errors, using the capture blocks as silent operators, and just giving up hope that someone can correct this situation in some way.
Global Capture
If it is a bad idea to use non-custom exceptions and catch all possible exceptions, then why does the language even allow this? There is one exception to the rule that always uses and catches a specific exception, that is, the global capture rule. A global capture block is the highest level capture block and must catch all exceptions that bubbling to that level. PHP itself contains a (have you seen the "Fatal Error: Uncaught Exception in..." message?), but you can override it with a custom handler to serve as a fallback. You can set this handler with the set_exception_handler()
function, so you can do it as you like and add a rule to your PHPMD rule set that prohibits lines like "catch (Exception $e) {
". This is the only reason for a general exception handler that should be found in production code, which captures every instance of the Exception
class that has not been caught yet. Other handlers must be specific and limited to exceptions that it knows how to handle and be responsible. Going cautious here, letting a handleable exception bubbling once (and then fixing it in code) is definitely much better than catching too much and acting as a silent operator.
Summary
In short, an exception is thrown only when your code cannot complete the requested instruction with the given input, always throwing a custom exception that actually tells the calling code that is currently in the case, and if you call other code , then only catches exceptions that you can and should handle. This will make your components less like black boxes (custom exceptions) and reduce the possibility that developers integrating your components must change your code (don't catch exceptions you shouldn't). We always tell our customers/managers to be specific, but we should be specific too!
(Picture from Fotolia)
Frequently Asked Questions about PHP Exception Handling
PHP exception handling is a powerful mechanism that allows developers to hypervise the errors and exceptions that may occur during execution of a program. It provides a way to transfer control from one part of the program to another. PHP exception handling is used to change the normal flow of code execution when a specified error occurs. This can make the code easier to read and manage because it separates the error handling code from the main program logic.
In PHP, the try-catch block is used to handle exceptions. The try block contains code that may throw exceptions, while the catch block contains code that will be executed if an exception is thrown in the try block. If an exception is thrown in the try block, the script stops running and control is passed to the first catch block matching the thrown exception type.
The finally block in PHP exception handling is used to ensure that a piece of code is always executed, whether an exception is thrown or not. This is useful for cleaning activities such as closing files or database connections that should be performed regardless of success or failure of operations.
In PHP, you can create custom exceptions by extending the built-in Exception class. This allows you to add custom functionality to exceptions, or create application domain-specific exceptions. To create a custom exception, you can define a new class that extends Exception and then add any custom methods or properties you want.
In PHP, errors are a serious problem that prevents scripts from running, while exceptions are a condition that changes the normal execution process. Errors are usually caused by syntax errors or calling undefined functions. On the other hand, exceptions are often used to handle conditions that are not fatal to a program but require special handling.
In PHP, you can use multiple catch blocks to handle multiple exceptions. Each catch block handles exceptions of a specific type. When an exception is thrown, the catch block is checked in the order that appears in the code. The first catch block capable of handling the thrown exception type will be executed.
Yes, you can re-throw the exception in PHP. This is very useful if you want to handle exceptions somehow but want to have a higher level of exception handler catch it. To re-throw the exception, just use the throw statement in the catch block.
In PHP, you can log exceptions by using the error_log function in the catch block. This allows you to log information about the exception, including its messages and stack traces, into the specified log file.
PDOException is an exception that is thrown when an error occurs in a PDO operation. PDO (PHP Data Object) is a database abstraction layer that provides a consistent interface for accessing databases in PHP. PDOException provides information about errors, including SQLSTATE error codes and error messages for the database driver.
In PHP, you can handle uncaught exceptions by defining a custom exception handler function and then setting it as the default exception handler using the set_exception_handler function. This function is called whenever an exception that is not caught by the try-catch block is thrown.
The above is the detailed content of PHP Master | Exceptional Exceptions. For more information, please follow other related articles on the PHP Chinese website!