PHP 튜토리얼

PHP 홈 PHP 소개 PHP 설치 PHP 구문 PHP 주석 PHP 변수 PHP 에코 / 인쇄 PHP 데이터 유형 PHP 문자열 PHP 숫자 PHP 수학 PHP 상수 PHP 연산자 PHP If...Else...Elseif PHP 스위치 PHP 루프 PHP 함수 PHP 배열 PHP 슈퍼글로벌 PHP 정규식

PHP 양식

PHP 양식 처리 PHP 양식 유효성 검사 PHP 양식 필요 PHP 양식 URL/이메일 PHP 양식 완성

PHP 고급

PHP 날짜 및 시간 PHP 포함 PHP 파일 처리 PHP 파일 열기/읽기 PHP 파일 생성/쓰기 PHP 파일 업로드 PHP 쿠키 PHP 세션 PHP 필터 PHP 필터 고급 PHP 콜백 함수 PHP JSON PHP 예외

PHP OOP

PHP OOP란? PHP 클래스/객체 PHP 생성자 PHP 소멸자 PHP 액세스 수정자 PHP 상속 PHP 상수 PHP 추상 클래스 PHP 인터페이스 PHP 특성 PHP 정적 메서드 PHP 정적 속성 PHP 네임스페이스 PHP 반복 가능

MySQL 데이터베이스

MySQL 데이터베이스 MySQL 연결 MySQL 생성 DB MySQL 테이블 생성 MySQL 삽입 데이터 MySQL 마지막 ID 가져오기 MySQL은 다중 삽입 MySQL 준비 MySQL 선택 데이터 MySQL 어디 MySQL 주문 기준 MySQL 데이터 삭제 MySQL 업데이트 데이터 MySQL 제한 데이터

PHP XML

PHP XML 파서 PHP SimpleXML 파서 PHP SimpleXML - 가져오기 PHP XML 국외 거주자 PHP XML DOM

PHP - AJAX

AJAX 소개 AJAX PHP AJAX 데이터베이스 AJAX XML AJAX 라이브 검색 AJAX 투표

PHP 예제

PHP 예제 PHP 컴파일러 PHP 퀴즈 PHP 연습 PHP 인증서

PHP 참조

PHP 개요 PHP 배열 PHP 캘린더 PHP 날짜 PHP 디렉토리 PHP 오류 PHP 예외 PHP 파일 시스템 PHP 필터 PHP FTP PHP JSON PHP 키워드 PHP 라이브러리 XML PHP 메일 PHP 수학 PHP 기타 PHP MySQLi PHP 네트워크 PHP 출력 제어 PHP 정규식 PHP SimpleXML PHP 스트림 PHP 문자열 PHP 변수 처리 PHP XML 파서 PHP 우편번호 PHP 시간대

PHP 예외


예외란 무엇입니까?

예외는 PHP 스크립트의 오류 또는 예기치 않은 동작을 설명하는 개체입니다.

많은 PHP 함수와 클래스에서 예외가 발생합니다.

사용자 정의 함수 및 클래스도 예외를 throw할 수 있습니다.

예외는 사용할 수 없는 데이터를 발견했을 때 함수를 중지하는 좋은 방법입니다.


예외 발생

throw명령문을 사용하면 사용자 정의 함수 또는 메서드에서 예외를 throw할 수 있습니다 . 예외가 발생하면 다음 코드가 실행되지 않습니다.

예외가 catch되지 않으면 "Uncaught Exception" 메시지와 함께 치명적인 오류가 발생합니다.

캐치하지 않고 예외를 던질 수 있습니다.

예시

<?php
function divide($dividend, $divisor) {
  if($divisor == 0) {
    throw new Exception("Division by zero");
  }
  return $dividend / $divisor;
}

echo divide(5, 0);
?>

결과는 다음과 같습니다.

Fatal error: Uncaught Exception: Division by zero in C:\webfolder\test.php:4
Stack trace: #0 C:\webfolder\test.php(9):
divide(5, 0) #1 {main} thrown in C:\webfolder\test.php on line 4

try...catch 문

위 예제의 오류를 피하기 위해 try...catch명령문을 사용하여 예외를 포착하고 프로세스를 계속할 수 있습니다.

통사론

try {
  code that can throw exceptions
} catch(Exception $e) {
  code that runs when an exception is caught
}

예시

예외가 발생하면 메시지 표시:

<?php
function divide($dividend, $divisor) {
  if($divisor == 0) {
    throw new Exception("Division by zero");
  }
  return $dividend / $divisor;
}

try {
  echo divide(5, 0);
} catch(Exception $e) {
  echo "Unable to divide.";
}
?>

catch 블록은 catch해야 하는 예외 유형과 예외에 액세스하는 데 사용할 수 있는 변수 이름을 나타냅니다. 위의 예에서 예외 유형은 Exception이고 변수 이름은 $e입니다.


try...catch...finally 문

명령문 은 try...catch...finally예외를 잡는 데 사용할 수 있습니다. 블록 의 코드 finally는 예외가 포착되었는지 여부에 관계없이 항상 실행됩니다. finally존재하는 경우 블록 catch은 선택 사항입니다.

통사론

try {
  code that can throw exceptions
} catch(Exception $e) {
  code that runs when an exception is caught
} finally {
  code that always runs regardless of whether an exception was caught
}

예시

예외가 발생하면 메시지를 표시한 다음 프로세스가 종료되었음을 나타냅니다.

<?php
function divide($dividend, $divisor) {
  if($divisor == 0) {
    throw new Exception("Division by zero");
  }
  return $dividend / $divisor;
}

try {
  echo divide(5, 0);
} catch(Exception $e) {
  echo "Unable to divide. ";
} finally {
  echo "Process complete.";
}
?>

예시

예외가 catch되지 않은 경우에도 문자열을 출력합니다.

<?php
function divide($dividend, $divisor) {
  if($divisor == 0) {
    throw new Exception("Division by zero");
  }
  return $dividend / $divisor;
}

try {
  echo divide(5, 0);
} finally {
  echo "Process complete.";
}
?>

예외 객체

예외 개체에는 함수에서 발생한 오류 또는 예기치 않은 동작에 대한 정보가 포함되어 있습니다.

통사론

new Exception(message, code, previous)

매개변수 값

Parameter Description
message Optional. A string describing why the exception was thrown
code Optional. An integer that can be used used to easily distinguish this exception from others of the same type
previous Optional. If this exception was thrown in a catch block of another exception, it is recommended to pass that exception into this parameter

행동 양식

예외를 잡을 때 다음 표는 예외에 대한 정보를 얻는 데 사용할 수 있는 몇 가지 방법을 보여줍니다.

Method Description
getMessage() Returns a string describing why the exception was thrown
getPrevious() If this exception was triggered by another one, this method returns the previous exception. If not, then it returns null
getCode() Returns the exception code
getFile() Returns the full path of the file in which the exception was thrown
getLine() Returns the line number of the line of code which threw the exception

예시

발생한 예외에 대한 출력 정보:

<?php
function divide($dividend, $divisor) {
  if($divisor == 0) {
    throw new Exception("Division by zero", 1);
  }
  return $dividend / $divisor;
}

try {
  echo divide(5, 0);
} catch(Exception $ex) {
  $code = $ex->getCode();
  $message = $ex->getMessage();
  $file = $ex->getFile();
  $line = $ex->getLine();
  echo "Exception thrown in $file on line $line: [Code $code]
  $message";
}
?>

완전한 예외 참조

전체 참조를 보려면 전체 PHP 예외 참조 로 이동하십시오 .

참조에는 모든 Exception 메서드에 대한 설명과 예가 포함되어 있습니다.