- Php
- Features
- Autoload
- Class Reflection
- Magic Methods
- Exceptions ♣
- Late Static Binding
- Type Hinting
- Spl
- Phpunit
- Phar
- Composer
- Guzzle
- Carbon
- Faker
- Math
- Requests
- Design Patterns
- Singleton Pattern
- Observer Pattern
- Strategy Pattern
- Registry
- Symfony
- Routes
- Annotations
- Flex
- Controllers
- Doctrine
- Templating
- Versions
- Php7.4
- Php8.0
- Modern Php
- Composer
- Slim Framework
- Autoloader
- Package
- Releases
- Generators
- Dependency Injection
- Middleware
- Framework
- App
- Http Foundation
- Front Controller
- Routing
- Render Controller
- Resolver
- Soc
- Frameworks
- Symfony V5
- Laravel V8
- Laminas V3
- Codeigniter V4
Try Catch
An exception from a try block is passed on to catch block.
try {
//$number = 1/0;
$number = -1;
if ($number < 0) {
throw new Exception ("The number is negative");
}
} catch (Exception $e) {
echo $e->getMessage(); // Division by zero
}
Exception class can be extended, to use different nested try/catch blocks.
code
class MyException extends Exception {}
try {
$number = -1;
if ($number < 0) {
throw new MyException("Invalid number");
}
$number = 1/0;
} catch (Exception $e) {
echo $e->getMessage(); // Division by zero
} catch (MyException $e) {
echo $e->getMessage(); // Division by zero
}
PHP allows to define a catch-all function that is automatically called.
function handleUncaughtExcetion($e) {
echo $e->getMessage();
}
set_exception_handler("handleUncaughtExcetion");
throw new Exception ("My error!"); // My error!
echo "This is never displayed";
// Without exception handler, we will have:
// Uncaught exception 'Exception' with message 'My error!'