php error exception handling mechanism of supplement

  • 2020-05-17 04:54:06
  • OfStack

1. Error handling
Exception handling: unexpected, unexpected things that happen during a program's run. Use exceptions to change the normal flow of the script
One of the new important features in PHP5
 
if(){ 
}else{ 
} 
try { 
}catch( The exception object ){ 
} 

1. If there is no problem with the code in try, then the code in try will be executed after the completion of catch
2. If an exception occurs in the code in try, an exception object (using throw) is thrown to the parameter in catch, and the code will not continue to execute in try
Jump directly to catch to execute, catch to complete, and then continue to execute
Note: this is not the main thing we need to do. We need to solve this exception in catch. If we can't solve it, we will give it to the user
2. Define an exception class yourself
What it does: write one or more methods to handle the exception when it occurs
1. Define your own exception class, which must be a subclass of Exception(built-in class).
2. Only constructors and toString() in the Exception class can be overridden, the rest are final
3. Handle multiple exceptions
If an exception is thrown in a method when you define your own function class
 
class OpenFileException extends Exception { 
function __construct($message = null, $code = 0){ 
parent::__construct($message, $code); 
echo "wwwwwwwwwwwwwww<br>"; 
} 
function open(){ 
touch("tmp.txt"); 
$file=fopen("tmp.txt", "r"); 
return $file; 
} 
} 
class DemoException extends Exception { 
function pro(){ 
echo " To deal with demo Abnormal occurrence <br>"; 
} 
} 
class TestException extends Exception { 
function pro(){ 
echo " Here to deal with test Abnormal occurrence <br>"; 
} 
} 
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(" Demonstrate an exception "); 
} 
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<br>"; 
$my=new MyClass(); 
$my->openfile(); 
$my->demo(0); 
$my->test(0); 
$my->fun(1); 
echo "22222222222222222<br>"; 
}catch(OpenFileException $e){ //$e =new Exception(); 
echo $e->getMessage()."<br>"; 
$file=$e->open(); 
}catch(DemoException $e){ 
echo $e->getMessage()."<br>"; 
$e->pro(); 
}catch(TestException $e){ 
echo $e->getMessage()."<br>"; 
$e->pro(); 
}catch(Exception $e){ 
echo $e->getMessage()."<br>"; 
} 
var_dump($file); 
echo "444444444444444444444<br>"; 

Related articles: