클래스 Exception
클래스 Exception은 PHP에서 모든 예외의 기본 클래스를 나타냅니다.
예외 작업을 위한 기본 메서드들을 포함하고 있습니다: 오류 메시지 얻기,
오류 코드, 예외가 발생한 파일 및 줄, 그리고 호출 스택입니다.
예외를 생성할 때 메시지, 오류 코드, 그리고 이전 예외를 전달할 수 있습니다.
문법
new Exception(string $message = "", int $code = 0, Throwable $previous = null);
예시
간단한 예외를 생성하고 처리해 봅시다:
<?php
try {
throw new Exception('Something went wrong', 100);
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
?>
코드 실행 결과:
'Error: Something went wrong'
예시
Exception 클래스의 주요 메서드를 사용해 봅시다:
<?php
try {
throw new Exception('Test exception', 123);
} catch (Exception $e) {
echo 'Message: ' . $e->getMessage() . "\n";
echo 'Code: ' . $e->getCode() . "\n";
echo 'File: ' . $e->getFile() . "\n";
echo 'Line: ' . $e->getLine() . "\n";
}
?>
코드 실행 결과 (예시):
'Message: Test exception
Code: 123
File: /path/to/file.php
Line: 3'
예시
예외 발생 시 호출 스택을 얻어 봅시다:
<?php
function test() {
throw new Exception('Stack trace test');
}
try {
test();
} catch (Exception $e) {
print_r($e->getTrace());
}
?>
코드 실행 결과 (예시):
[
[
'file' => '/path/to/file.php',
'line' => 5,
'function' => 'test',
'args' => []
]
]
함께 보기
-
클래스
ErrorException,
오류를 예외로 나타냅니다 -
함수
set_exception_handler,
사용자 정의 예외 처리기를 설정합니다