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 메서드에 대한 설명과 예가 포함되어 있습니다.