search
HomeBackend DevelopmentPHP TutorialPHP exception error handling mechanism and error handling (1/2)_PHP tutorial

PHP exception error handling mechanism and error handling (1/2)_PHP tutorial

Jul 13, 2016 am 10:55 AM
catchphptryandexistdeal withabnormalushavemechanismusethismistake

The most common error mechanism we use in PHP is try catch{}, which can easily catch errors. However, PHP also provides error viewing and error closing for many things. This can be found in php.ini During processing, you can also add error_display(0); at the beginning of the file to not display errors

The code is as follows Copy code
 代码如下 复制代码

$a = fopen('test.txt','r');
//这里并没有对文件进行判断就打开了,如果文件不存在就会报错
?>

$a = fopen('test.txt','r'); //The file is opened here without judging it. If the file does not exist, an error will be reported
 代码如下 复制代码

if(file_exists('test.txt')){
$f=fopen('test.txt','r');
//使用完后关闭
fclose($f);
}
?>

?>


Then the correct way to write it should be as follows:
The code is as follows Copy code
 代码如下 复制代码

if(!file_exists('aa.txt')){
die('文件不存在');
} else {
//执行操作
}
//如果上面die()被触发,那么这里echo接不被执行
echo 'ok';

if(file_exists('test.txt')){

$f=fopen('test.txt','r');

//Close after use
 代码如下 复制代码

file_exits('aaa.txt') or die('文件不存在');
echo 'ok';

fclose($f); } ?> 1. Three methods of PHP error handling A. Simple die() statement; Equivalent to exit(); Example:
The code is as follows Copy code
if(!file_exists('aa.txt')){ die('File does not exist'); } else { //Perform operation } //If die() above is triggered, then the echo connection here will not be executed echo 'ok';
Concise writing:
The code is as follows Copy code
file_exits('aaa.txt') or die('File does not exist'); echo 'ok';

B. Custom errors and error triggers

1. Error handler (custom error, generally used for syntax error handling)
Create a custom error function (handler) that must be able to handle at least two parameters (error_level and errormessage), but can accept up to five parameters (error_file, error_line, error_context)
Syntax:

function error_function($error_level,$error_message,$error_file,$error_line,$error_context)
//After creation, you need to rewrite the set_error_handler(); function
set_error_handler('error_function',E_WARNING); //Here error_function corresponds to the custom handler name created above, and the second parameter is the error level using the custom error handler;

Error reporting level (just understand it)

These error reporting levels are different types of errors that error handlers are designed to handle:

Value Constant Description
2 E_WARNING Nonfatal run-time error. Do not pause script execution.
8 E_NOTICE Run-time notification.

Script discovery errors may occur, but may also occur while the script is running normally.

256 E_USER_ERROR Fatal user-generated error. This is similar to E_ERROR set by the programmer using the PHP function trigger_error().
512 E_USER_WARNING Non-fatal user-generated warning. This is similar to the E_WARNING set by the programmer using the PHP function trigger_error().
1024 E_USER_NOTICE User-generated notification. This is similar to E_NOTICE set by the programmer using the PHP function trigger_error().
4096 E_RECOVERABLE_ERROR Trapable fatal error. Like E_ERROR, but can be caught by a user-defined handler. (see set_error_handler())
8191 E_ALL All errors and warnings except level E_STRICT.

(In PHP 6.0, E_STRICT is part of E_ALL)

2. Error trigger (generally used to handle logical errors)
Requirement: For example, if you want to receive an age, if the number is greater than 120, it is considered an error
Traditional method:

if($age>120){
echo 'Wrong age';exit();
}

Use triggers:

if($age>120){
//trigger_error('error message'[,'error level']); The error level here is optional and is used to define the level of the error
//User-defined levels include the following three types: E_USER_WARNING, E_USER_ERROR, E_USER_NOTICE
trigger_error('age error');//This is the default error handling method of the calling system, we can also use a custom processor
}
//Custom processor, same as above
function myerror($error_level,$error_message){
echo 'error text';
}
//At the same time, the system default processing function needs to be changed
set_error_handler('myerror',E_USER_WARNING);//Same as above, the first parameter is the name of the custom function, and the second parameter is the error level [The error levels here are usually the following three: E_USER_WARNING, E_USER_ERROR, E_USER_NOTICE]
//Now you can use the custom error handling function by using trigger_error

Practice questions:

The code is as follows Copy code
 代码如下 复制代码

date_default_timezone_set('PRC');
function myerror($error_level,$error_message){
$info= "错误号:$error_leveln";
$info.= "错误信息:$error_messagen";
$info.= '发生时间:'.date('Y-m-d H:i:s');
$filename='aa.txt';
if(!$fp=fopen($filename,'a')){
'创建文件'.$filename.'失败';
}
if(is_writeable($filename)){
if(!fwrite($fp,$info)){
echo '写入文件失败';
} else {
echo '已成功记录错误信息';
}
fclose($fp);
} else {
echo '文件'.$filename.'不可写';
}
exit();
}
set_error_handler('myerror',E_WARNING);
$fp=fopen('aaa.txt','r');
?>

date_default_timezone_set('PRC'); function myerror($error_level,$error_message){

$info= "Error number: $error_leveln";

$info.= "Error message: $error_messagen"; $filename='aa.txt'; if(!$fp=fopen($filename,'a')){ 'Create file'.$filename.'Failed'; } if(is_writeable($filename)){ if(!fwrite($fp,$info)){ echo 'Failed to write file'; } else { echo 'Error message recorded successfully'; } fclose($fp);
} else { echo 'File'.$filename.'Not writable'; }
exit();
} set_error_handler('myerror',E_WARNING); $fp=fopen('aaa.txt','r'); ?>
1 2 http://www.bkjia.com/PHPjc/632215.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632215.htmlTechArticleThe most commonly used error mechanism we use in php is try catch{}, which can be easily caught. Errors have been detected, but in php, error viewing and error closing are also provided for many...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.