예외는 프로그램 실행 중에 발생한 문제입니다. 프로그램을 실행하는 동안 예외가 발생하면 명령문 뒤에 오는 코드는 실행되지 않으며 PHP는 일치하는 첫 번째 catch 블록을 찾으려고 시도합니다. 예외가 catch되지 않으면 "Uncaught Exception"과 함께 PHP 치명적인 오류가 발생합니다.
구문
try {
print "this is our try block";
throw new Exception();
}catch (Exception $e) {
print "something went wrong, caught yah! n";
}finally {
print "this part is always executed";
} 예시
<?php
function printdata($data) {
try {
//If var is six then only if will be executed
if($data == 6) {
// If var is zero then only exception is thrown
throw new Exception('Number is six.');
echo "\n After throw (It will never be executed)";
}
}
// When Exception has been thrown by try block
catch(Exception $e){
echo "\n Exception Caught", $e->getMessage();
}
//this block code will always executed.
finally{
echo "\n Final block will be always executed";
}
}
// Exception will not be rised here
printdata(0);
// Exception will be rised
printdata(6);
?> 출력
Final block will be always executed Exception CaughtNumber is six. Final block will be always executed
참고
예외를 처리하려면 프로그램 코드가 try 블록 안에 있어야 합니다. 각 시도에는 적어도 하나의 개별 catch 블록이 있어야 합니다. 여러 catch 블록을 사용하여 다양한 예외 클래스를 잡을 수 있습니다.