PHP에서 오류와 예외의 차이점은 무엇입니까
인터넷에서 오류와 예외의 차이점에 대한 대부분의 정보는 Java로 설명되어 있습니다. PHP의 예외 처리 프로세스는 Java의 예외 처리 프로세스와 유사한 것 같습니다. 오류와 예외의 차이점과 캡처를 알아보겠습니다. PHP가 필요한 친구들이 참고할 수 있습니다.
JSON 파싱 코드를 작성했습니다. 데이터 소스가 JSON임을 보장하지 않으므로 파싱이 실패할 수 있습니다. 그러나 PHP의 json_decode는 구문 분석할 수 없는 문자열을 발견할 때 오류를 보고하지 않으며 직접 빈 값을 반환합니다. 그리고 구문 분석이 가능하더라도 내부 필드가 항상 일관적이라는 것을 믿을 수 없습니다. 따라서 JSON으로 구문 분석할 수 있는지 여부뿐만 아니라 필드가 누락되었는지 여부도 확인해야 합니다. 게으른 나머지 예외만 잡아내고 싶은데, 예를 들어
Trying to get property of non-object
Trying to get property of non-object
但是,下面的 try catch 怎么也捕获不到异常
try { // Code that may throw an Exception or Error. } catch (\Exception $t) { // Handle exception }
Google 了一下,才知道,PHP 中除了 Exception 还有 Error 的概念,而 Trying to get property of non-object,很不幸就属于 Error。
PHP 中 error 与 exception 的区别
看了几篇关于 PHP error 和 exception 区别的介绍文章,感觉都没有说到点上。我突然想,我为啥一定要知道他们的区别,因为我觉得这个设计是有问题的。例如,PHP5 时代,try catch 只能捕获 Exception,而不能捕获 Error。我非常不能理解 PHP 5 这种设计的意义是什么?而 PHP7 的处理方式,说明了我的观点是正确的。所以,我就没有兴趣去深究其起初的设计思路了。
PHP 7 的新特性
From now on, most of the errors are reported through the exception class Error.
interface Throwable |- Error implements Throwable |- ArithmeticError extends Error |- DivisionByZeroError extends ArithmeticError |- AssertionError extends Error |- ParseError extends Error |- TypeError extends Error |- ArgumentCountError extends TypeError |- Exception implements Throwable |- ClosedGeneratorException extends Exception |- DOMException extends Exception |- ErrorException extends Exception |- IntlException extends Exception |- LogicException extends Exception |- BadFunctionCallException extends LogicException |- BadMethodCallException extends BadFunctionCallException |- DomainException extends LogicException |- InvalidArgumentException extends LogicException |- LengthException extends LogicException |- OutOfRangeException extends LogicException |- PharException extends Exception |- ReflectionException extends Exception |- RuntimeException extends Exception |- OutOfBoundsException extends RuntimeException |- OverflowException extends RuntimeException |- PDOException extends RuntimeException |- RangeException extends RuntimeException |- UnderflowException extends RuntimeException |- UnexpectedValueException extends RuntimeException
이제부터 대부분의 오류는 Error 예외 클래스를 통해 보고됩니다.
즉, PHP 7부터는 Error와 Exception이 모두 Throwable에서 상속됩니다. .
Throwable의 상속 관계를 보면 Error와 Exception이 동일한 수준의 관계에 있음을 알 수 있습니다.
try { // Code that may throw an Exception or Error. } catch (\Throwable $t) { // Handle exception }
비객체의 속성을 가져오는 방법을 캡처합니다.
try { // Code that may throw an Exception or Error. } catch (\Throwable $t) { // Executed only in PHP 7, will not match in PHP 5.x } catch (\Exception $e) { // Executed only in PHP 5.x, will not be reached in PHP 7 }
PHP 5 및 PHP 7 작성 방법과 모두 호환됩니다.
{ public function getMessage(): string; // Error reason public function getCode(): int; // Error code public function getFile(): string; // Error begin file public function getLine(): int; // Error begin line public function getTrace(): array; // Return stack trace as array like debug_backtrace() public function getTraceAsString(): string; // Return stack trace as string public function getPrevious(): Throwable; // Return previous `Trowable` public function __toString(): string; // Convert into string }
일부 내장 방법
인터페이스 Throwable
rrreee
특정 정보를 기록합니다. 예외예를 들어오류 코드 파일, 줄 번호, 특정 오류 메시지, 오류 유형
더 정확한 캡처 또는 더 넓은 캡처를 사용🎜🎜또는 점수 상황🎜🎜예를 들어 MySQL의 고유 인덱스 예외, 정확한 캡처에 익숙합니다. . 특별한 처리가 필요하기 때문입니다. 🎜🎜다른 대부분의 경우에는 Throwable을 광범위하게 캡처하는 것 같아요. 그 이유는 try catch가 일반적으로 논리에 영향을 주지 않는 낮은 확률의 예외와 같은 예외를 무시하는 데 사용되기 때문입니다. 처리할 필요가 없으므로 로그가 기록되는 한 특정 예외는 그다지 중요하지 않습니다. 🎜🎜추천 학습: 🎜php 비디오 튜토리얼🎜🎜위 내용은 PHP에서 오류와 예외의 차이점은 무엇입니까의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제









이번 장에서는 CakePHP의 환경 변수, 일반 구성, 데이터베이스 구성, 이메일 구성에 대해 알아봅니다.

PHP 8.4는 상당한 양의 기능 중단 및 제거를 통해 몇 가지 새로운 기능, 보안 개선 및 성능 개선을 제공합니다. 이 가이드에서는 Ubuntu, Debian 또는 해당 파생 제품에서 PHP 8.4를 설치하거나 PHP 8.4로 업그레이드하는 방법을 설명합니다.

CakePHP에서 데이터베이스 작업은 매우 쉽습니다. 이번 장에서는 CRUD(생성, 읽기, 업데이트, 삭제) 작업을 이해하겠습니다.

CakePHP는 PHP용 오픈 소스 프레임워크입니다. 이는 애플리케이션을 훨씬 쉽게 개발, 배포 및 유지 관리할 수 있도록 하기 위한 것입니다. CakePHP는 강력하고 이해하기 쉬운 MVC와 유사한 아키텍처를 기반으로 합니다. 모델, 뷰 및 컨트롤러 gu
