views:

127

answers:

2

Can I declare a function in php that throws an exception? For example:

public function read($b, $off, $len) throws IOException 
+4  A: 

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';
?>
injekt
yes i read it , by i was thinking maybe it posible and i missed the tutorial . ok so i cant declare a method that throws an exception ?what about IOException there is such thing o i need to create it my self?
shay
No, it doesn't exist already. But you can declare it (extend an appropriate SPL exception ( `class IOException extends RuntimeException {}`)
ircmaxell
+2  A: 

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.

Brad F Jacobs
thank you what about declaring the function as throwing an exception?i just need to throw the exception
shay
Do i must catch every exception , also if it a simple exception like OutOfRangeException? cant i run code without catching any exception ?
shay