Home >Backend Development >PHP Problem >How to use try...case syntax in PHP?

How to use try...case syntax in PHP?

慕斯
慕斯Original
2021-06-16 17:27:222802browse

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.

How to use try...case syntax in PHP?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( &#39;对不起,出错了&#39;);
}catch(Exception $e){
 echo $e->getMessage();
}
?>

Running results As follows:

How to use try...case syntax in PHP?

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 &#39;恭喜你,正确&#39; ;
        }else{
            throw new Exception( &#39;对不起,出错了&#39;);
        }
}catch(Exception $e){
 echo $e->getMessage();
}
?>

The running results are as follows:

How to use try...case syntax in PHP?

When we manually throw the exception object, the code is as follows:

<?php
//try.. .catch( )语法
try{
     //尝试执行本区间代码,如果出错抛出一个异常
     //抛出给catch来接收处理
     if(4>5){
        echo &#39;恭喜你,正确&#39; ;
        }else{
            throw new Exception( &#39;对不起,出错了&#39;);
        }
}catch(Exception $e){
 echo $e->getMessage();
}
?>

The running results are as follows:

How to use try...case syntax in PHP?

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!

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

Related articles

See more