Use of try catch in PHP

little bottle
Release: 2023-04-05 21:14:01
forward
10833 people have browsed it

1.try catch can catch the exception thrown by the upper layer

2.finally is a block that will eventually be executed regardless of whether try or catch has a return block

3.try can also be used Catch the throw exception inside the call_user_func_array callback function class

4. call_user_func_array can only call the static method of the class, and you can create a new object in this static method

5. Without customizing anything In the case of error handling functions, try cannot capture errors in PHP itself, including notice warning error and other levels.

The following code is a part of the project, which has gone through multiple layers of calls and callbacks


<?php
class Oss {
    public static function connect() {
    	throw new Exception("oss connect error");
    	return &#39;oss object&#39;;
    }
}
//调用三层
class S3{
	public static function connect() {
		//throw new Exception("s3 connect error");
    	return &#39;s3 object&#39;;
    }
}
//调用二层
function callReader($class,$url){
	try{
		$conn=call_user_func_array(array($class, "connect"),array());
		return $conn;
	}catch(Exception $e){
		throw $e;	
	}finally{
		//无论如何都会执行,在这记录日志
	}
}
//调用一层
function getMessage(){
	$conn=null;
	try {
	    $conn=callReader(&#39;Oss&#39;,"http://xxxx");
	} catch (Exception $e1) {
		$conn=callReader(&#39;S3&#39;,"http://xxxx");
	}
	return $conn;
}
//最先的入口
try{
	var_dump(getMessage());
}catch(Exception $e){}
Copy after login

【Course Recommendation: PHP Video Tutorial】 

The above is the detailed content of Use of try catch in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:cnblogs.com
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template