Can I declare a function in php that throws an exception? For example:
public function read($b, $off, $len) throws IOException
Can I declare a function in php that throws an exception? For example:
public function read($b, $off, $len) throws IOException
You could throw a new exception from the body of the function. It's all described here
Example:
<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
else return 1/$x;
}
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
// Continue execution
echo 'Hello World';
?>
For a list of exceptions that come with the SPL: SPL Exceptions.
If you want to create your own exception:
From the PHP Exceptions page:
The thrown object must be an instance of the Exception Class or a subclass of Exception. Trying to throw an object that is not will result in a PHP Fatal Error.
So yes, it is possible to create your own exceptions. Just a bit of reading will help you achieve what you want.