Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> PHP

PHP ErrorException

Giới thiệu

Lớp Exception của PHP triển khai interface Throwable. Lớp ErrorException kế thừa Exception. ErrorException dùng để ném rõ ràng khi muốn bắt và xử lý lỗi thường bị bỏ qua như Notice hay Warning.

PHP core có các hằng số lỗi định nghĩa sẵn:

Giá trịHằng sốMô tả
1E_ERRORLỗi chạy chết người (fatal).
2E_WARNINGCảnh báo chạy (lỗi không fatal).
4E_PARSELỗi parse compile-time.
8E_NOTICEThông báo chạy.
16E_CORE_ERRORLỗi fatal khi khởi động PHP.
32E_CORE_WARNINGCảnh báo khi khởi động PHP.
64E_COMPILE_ERRORLỗi fatal compile-time.
128E_COMPILE_WARNINGCảnh báo compile-time.
256E_USER_ERRORThông báo lỗi do user tạo.
512E_USER_WARNINGCảnh báo do user tạo.
1024E_USER_NOTICEThông báo do user tạo.
2048E_STRICTPHP đề xuất thay đổi code để tương thích.
4096E_RECOVERABLE_ERRORLỗi fatal có thể bắt.
8192E_DEPRECATEDThông báo chạy lỗi thời.
16384E_USER_DEPRECATEDCảnh báo do user tạo lỗi thời.
32767E_ALLTất cả lỗi và cảnh báo, bao gồm E_STRICT.

Ngoài thuộc tính/phương thức kế thừa từ Exception, ErrorException thêm một thuộc tính và một phương thức:

protected int severity; final public getSeverity ( void ) : int

Mức độ exception biểu diễn bằng số nguyên liên kết loại lỗi trong bảng trên.

Ví dụ ErrorException

Script: hàm user errhandler đặt làm error handler bằng set_error_handler(). Nó ném ErrorException khi gặp lỗi fatal file không tìm thấy để đọc.

Ví dụ

<?php function errhandler($severity, $message, $file, $line) { if (!(error_reporting() & $severity)) { echo "no error"; return; } throw new ErrorException("Fatal Error: No such file or directory", 0, E_ERROR); } set_error_handler("errhandler"); try { $data = file_get_contents("nofile.php"); echo $data; } catch (ErrorException $e) { echo $e->getMessage(); } ?>

Kết quả:

Kết quả

Fatal Error: No such file or directory