Home > Article > Backend Development > How to deal with violations of regulations in other places? Supplementary PHP error and exception handling mechanisms
1. Error handling
Exception handling: Accidents are unexpected things that happen during the running of the program. Use exceptions to change the normal flow of the script
A new important feature in PHP5
Copy the code The code is as follows:
if(){
}else{
}
try {
}catch(Exception object){
}
Copy the code The code is as follows:
class OpenFileException extends Exception {function __construct($message = null, $code = 0){
parent::__construct($message, $code);
echo "wwwwwwwwwwwwwww
";
}
function open(){
touch( "tmp.txt");
$file=fopen("tmp.txt", "r");
return $file;
}
}
class DemoException extends Exception {
function pro(){
echo "Handle demo Exception that occurred
";
}
}
class TestException extends Exception {
function pro(){
echo "Exceptions that occurred in test are handled here
";
}
}
class HelloException extends Exception {
}
class MyClass {
function openfile(){
$file=@fopen("tmp.txt", "r");
if(!$file)
throw new OpenFileException("File opening failed");
}
function demo($num=0){
if($num==1)
throw new DemoException("Exception occurred in the demonstration");
}
function test($num=0){
if($num= =1)
throw new TestException("Test error");
}
function fun($num=0){
if($num==1)
throw new HelloException("######### ##");
}
}
try{
echo "11111111111111
";
$my=new MyClass();
$my->openfile();
$my->demo(0) ;
$my->test(0);
$my->fun(1);
echo "22222222222222222
";
}catch(OpenFileException $e){ //$e =new Exception() ;
echo $e->getMessage()."
";
$file=$e->open();
}catch(DemoException $e){
echo $e->getMessage( )."
";
$e->pro();
}catch(TestException $e){
echo $e->getMessage()."
";
$e- >pro();
}catch(Exception $e){
echo $e->getMessage()."
";
}
var_dump($file);
echo "44444444444444444444
" ;
The above introduces how to deal with violations in different places. The PHP error and exception handling mechanism is supplemented, including how to deal with violations in different places. I hope it will be helpful to friends who are interested in PHP tutorials.