Home >Backend Development >PHP Tutorial >Use of try catch in PHP

Use of try catch in PHP

little bottle
little bottleforward
2019-04-16 14:48:0210875browse

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){}

【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!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete