The previous article introduced you to "What are the basic knowledge points of databases in PHP? Basic statement? basic concept? 》, this article continues to introduce to you how to use try...case syntax in PHP? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Usage of try...case syntax:
try{ }catch(){ }catch(){ }
Let’s take the code as an example, try (try to execute a certain piece of code) in square brackets Execute the code in this section. If an error occurs, an exception will be thrown.
Throw it to catch to receive processing. Catch (receiving errors) is a bit like process control as a whole, but in fact it is not. So how do we throw it? Well, we can throw an exception directly through throw. We throw a message in throw and let catch receive it. Therefore, there must be an exception signal in catch. When we have the object, we can call this object. When we The running results show that there is an error in the syntax and the content we defined is not parsed, so no matter what content is replaced, it is wrong, so all the objects we define must be instances of Exception,
<?php //try.. .catch( )语法 try{ //尝试执行本区间代码,如果出错抛出一个异常 //抛出给catch来接收处理 throw new Exception( '对不起,出错了'); }catch(Exception $e){ echo $e->getMessage(); } ?>
Running results As follows:
Under normal circumstances, we try to execute a certain round of code, such as using an if statement, the code is as follows:
<?php //try.. .catch( )语法 try{ //尝试执行本区间代码,如果出错抛出一个异常 //抛出给catch来接收处理 if(4<5){ echo '恭喜你,正确' ; }else{ throw new Exception( '对不起,出错了'); } }catch(Exception $e){ echo $e->getMessage(); } ?>
The running results are as follows:
When we manually throw the exception object, the code is as follows:
<?php //try.. .catch( )语法 try{ //尝试执行本区间代码,如果出错抛出一个异常 //抛出给catch来接收处理 if(4>5){ echo '恭喜你,正确' ; }else{ throw new Exception( '对不起,出错了'); } }catch(Exception $e){ echo $e->getMessage(); } ?>
The running results are as follows:
Recommended learning: php video tutorial
The above is the detailed content of How to use try...case syntax in PHP?. For more information, please follow other related articles on the PHP Chinese website!