search
HomeBackend DevelopmentPHP TutorialAnalyze PHP5 exception handling with examples_PHP tutorial

Analyze PHP5 exception handling with examples_PHP tutorial

Jul 21, 2016 pm 02:52 PM
phpphp5deal withCase Analysisabnormalmoduleuseoflanguage

<?php
/**
* ■Exception handling in PHP5
*
* PHP 5 adds an exception handling module similar to other languages. Exceptions generated in PHP code can be thrown
* statement throws and is caught by a catch statement. Code that requires exception handling must be placed within the try code block, ending with
* Catch possible exceptions. Every try must have at least one corresponding catch. Use multiple catches
* Can catch exceptions generated by different classes. When the try code block no longer throws an exception or cannot find a matching catch
* When an exception is thrown, the PHP code will continue executing after jumping to the last catch. Of course, PHP
* Allow exceptions to be thrown again within catch blocks.
* When an exception is thrown, the subsequent code will not continue
* is executed, and PHP will try to find the first matching catch. If an exception is not caught and
* If there is no need to use set_exception_handler() for corresponding processing, then PHP will generate a
* A serious error, and the prompt message Uncaught Exception... (uncaught exception) is output.
*/
?>
<?php
/**
* Exception.php
*
* ■㈡The properties and methods of the built-in exception class in PHP5
* The following code is only to illustrate the structure of the built-in exception handling class. It is not a usable code with practical significance.
*/

class Exception{
protected $message = 'Unknown exception'; // Exception message
protected $code = 0; // User-defined exception code
protected $file; // The file name where the exception occurred
protected $line; // Code line number where the exception occurred

function __construct($message = null, $code = 0);
final function getMessage(); // Return exception message
final function getCode(); // Return exception code (code name)
final function getFile(); // Return the file name where the exception occurred
final function getLine(); // Returns the code line number where the exception occurred
final function getTrace(); // backtrace() array
final function getTraceAsString(); // The getTrace() information that has been formatted into a string

Overloadable methods
function __toString(); // Outputable string
}

?>

<?php
/**
* syntax .php
*/

//■㈢Grammar structure and analysis

//PHP has two formats for throwing exceptions, as follows

//【1】try...catch...
try {
//Perform abnormal operations, such as database errors and file errors
}catch (Exception $e){
//Print error message
}

//【2】throw
$message='I must be run in the try{} block. If an exception occurs, I ($message) will be returned (passed) to the instance of the exception object in catch(), such as $e above';
$code=123; //Error code number, you can use $e->getCode(); in the catch block to return my value 123, so that I can customize the error code number

throw new Exception($message,$code);

//Note when learning JAVA, PHP exception handling does not have throws

?>

<?php
/**
* Example.php
*/
//■㈣Two examples to master PHP exception handling


//Example [1] use try...catch
/* PDO connects to the mysql database. If you have not seen PDO, first look at the constructor of PDO, or skip Example 1 and look at Example 2 */
$dsn = 'mysql:host=localhost;dbname=testdb';
$user = 'dbuser';
$password = 'dbpass';

try {
$dbh = new PDO($dsn, $user, $password); //Creating a database connection object is prone to exceptions
echo 'If there is an exception above, I will not be displayed';
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->__toString();
}
?>

<?php
//Example[2] try..cathc and throw are used together
try {
$error = 'I threw an exception message and jumped out of the try block';
if(is_dir('./tests')){
echo 'do sth.';
}else{
throw new Exception($error,12345);
}
echo 'If there is an exception above, it won't be my turn! ~<br />',"n";
} catch (Exception $e) {
echo 'Catch exception: ', $e->getMessage(),$e->getCode(), "n<br />"; //Display $error and 123456
}
echo 'Continue execution';
?>

<?php
//PHP's processing is much easier to learn than JAVA, because JAVA has too many exception classes, throws, etc.
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/371514.htmlTechArticle<?php /** * ■㈠Exception handling in PHP5* * PHP 5 adds exceptions similar to other languages processing module. Exceptions generated in PHP code can be thrown by the throw * statement and caught by the catch statement...
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
How do you create and use an interface in PHP?How do you create and use an interface in PHP?Apr 30, 2025 pm 03:40 PM

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

What is the difference between crypt() and password_hash()?What is the difference between crypt() and password_hash()?Apr 30, 2025 pm 03:39 PM

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

How can you prevent Cross-Site Scripting (XSS) in PHP?How can you prevent Cross-Site Scripting (XSS) in PHP?Apr 30, 2025 pm 03:38 PM

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

What is autoloading in PHP?What is autoloading in PHP?Apr 30, 2025 pm 03:37 PM

Autoloading in PHP automatically loads class files when needed, improving performance by reducing memory use and enhancing code organization. Best practices include using PSR-4 and organizing code effectively.

What are PHP streams?What are PHP streams?Apr 30, 2025 pm 03:36 PM

PHP streams unify handling of resources like files, network sockets, and compression formats via a consistent API, abstracting complexity and enhancing code flexibility and efficiency.

What is the maximum size of a file that can be uploaded using PHP ?What is the maximum size of a file that can be uploaded using PHP ?Apr 30, 2025 pm 03:35 PM

The article discusses managing file upload sizes in PHP, focusing on the default limit of 2MB and how to increase it by modifying php.ini settings.

What is Nullable types in PHP ?What is Nullable types in PHP ?Apr 30, 2025 pm 03:34 PM

The article discusses nullable types in PHP, introduced in PHP 7.1, allowing variables or parameters to be either a specified type or null. It highlights benefits like improved readability, type safety, and explicit intent, and explains how to declar

What is the difference between the unset() and unlink() functions ?What is the difference between the unset() and unlink() functions ?Apr 30, 2025 pm 03:33 PM

The article discusses the differences between unset() and unlink() functions in programming, focusing on their purposes and use cases. Unset() removes variables from memory, while unlink() deletes files from the filesystem. Both are crucial for effec

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software