Đó là một ý tưởng tốt để đặt tên cho các lớp học ngoại lệ dựa trên những gì đã đi sai chứ không phải là nơi nó xảy ra. Lớp ConfigException trong các ví dụ trước đây được thiết kế để truyền đạt ý tưởng rằng họ là trường hợp ngoại lệ thường gây ra do cấu hình sai hoặc lỗi trong ứng dụng. | break In real life obviously we would do something more sophisticated than just echoing a string. But what if we want to handle only one of our exception subtypes here and handle the other type somewhere else It s simple we can rethrow it so it can be caught by a different method or object case ConfigException SQL_SYNTAX_ERROR throw e break It s a good idea to name exception classes based on what went wrong rather than where it occurred. The ConfigException class in the previous examples is intended to convey the idea that they are exceptions that are typically caused by misconfiguration or bugs in the application. Replacing built-in PHP fatal errors with exceptions Once we re using exceptions it s a bit irritating that errors from PHP are reported as PHP 4-style errors rather than as exceptions. But it is possible to build a bridge from the old error-handling system to the new. Although this will not catch all errors fatal runtime errors such as calling a nonexistent method on an object will not be reported it will make error handling more consistent. The first things we need are an exception class to distinguish the PHP errors from other exceptions and a simple error handler to receive a PHP error and throw an exception instead class ErrorFromPHPException extends Exception function PHPErrorHandler errno errstr errfile errline throw new ErrorFromPHPException errstr errno Now we can set the error handler. If we proceed to try to open a nonexistent file we will get an exception instead of the old-fashioned error oldHandler set_error_handler PHPErrorHandler fopen tmp non-existent r And if for some reason we want to return to the ordinary way of handling these errors we can do this set_error_handler oldHandler Don t overdo exceptions We want to avoid cluttering our code with too much error handling and exceptions help us do that since the catch statements can be fewer than error handling condi 30 CHAPTER 2 Objects in PHP tionals that have to test the .