How To Use Exceptions Handling in PHP Example ?
Teams applying “How To Use Exceptions Handling in PHP Example ?” in a production project can use learn more here to record implementation, review and debugging time, then compare that effort with tests and shipped functionality instead of treating activity as performance by itself.
Before copying the example into a live application, confirm version-specific behaviour with the PHP project and test it against the project’s actual database and runtime.
Hi guys,
Today i will explained How To Use Exceptions Handling in PHP. This example is so easy to use in php. The exception model similar to that of other programming languages. Exceptions are important and provides a better control over error handling.
Lets explain there new keyword related to exceptions.try,throw,catch block.
So let's start to the example.
try
Function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown".
Throw
This is how you trigger an exception. Each "throw" must have at least one "catch".
Catch
A "catch" block retrieves an exception and creates an object containing the exception information.
Example
In the above example $e->getMessage function is used to get error message. There are following functions which can be used from Exception class.
getMessage() - message of exception
getCode() - code of exception
getFile() - source filename
getLine() - source line
getTrace() - n array of the backtrace()
getTraceAsString() - formated string of trace
<?php
try {
$error = 'Always throw this error';
throw new Exception($error);
echo 'Never executed';
}catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
echo 'Hello World';
?>
Output
Caught exception: Always throw this error Hello World
Creating Custom Exception Handler
You can define your own custom exception handler. Use following function to set a user-defined exception handler function.
string set_exception_handler ( callback $exception_handler )
Example
<?php
function exception_handler($exception) {
echo "Uncaught exception: " , $exception->getMessage(), "\n";
}
set_exception_handler('exception_handler');
throw new Exception('Uncaught Exception');
echo "Not Executed\n";
?>
Output
Uncaught exception: Uncaught Exception
Now you can check your own.
- How To Use Php Conditional Statement Example
- How to Check if String Contains Regex in PHP?
- PHP Array_column() Function Example
- PHP Generate List of Random Numbers Between 0 and 100 Example
- How to User Login with Facebook in PHP?
- How to Explode Every Character into Array Using PHP Example?
- PHP Form Validation Tutorial
- PHP Convert XML to JSON Example