Throwable is the base interface for any launchable object.
Source: PHP - Throwable
Exception is the base class for all Exceptions in PHP 5 , and the base class of all user exceptions in PHP 7 .
Source: PHP - Exception
In short, capturing the interface is equivalent to capturing all the classes that implement it ...
- I do not know how I can call them
Imagine the following scenario: you extends the class \Exception
in your project, when you want to stop the execution of something and simply display the message, cast that class. But if there is a fatal error, literal exception, and so on, you display the error message and stop the script from running. Example:
<?php
try {
bar();
if (!baz())
throw new MinhaExcecao('A função baz() retornou falso.');
} catch (MinhaExcecao $e) {
echo $e -> getMessage();
// O script vai continuar a ser executado...
} catch (PDOException $e) {
die('PDO lançou uma exceção. Há algo errado na conexão/consulta do banco de dados.');
// O script não vai continuar a ser executado...
} catch (Throwable $e) {
die('Capturado alguma classe que implementa a interface Throwable');
// O script não vai continuar a ser executado...
}
echo 'foo';
If the function baz()
returns false, it will fall into block catch (MinhaExcecao $e)
with echo
and soon the script will continue in echo 'foo';
... In other cases, execution will be totally interrupted by function call die()
.
Remember that catch
works like a waterfall. When launching an object, it will be captured in the first block catch
compatible with the launched class / interface. This way, your custom class must be captured first or before your parent class or interface, or else it will not reach the desired catch
.
There is still the finally block , theoretically, is ALWAYS executed.
Extending the \Exception
class is very useful when you want to pass some error message to the user to which he did something wrong. The other messages are usually programmer errors or some feature that is not working properly. Then you'd better generate a log accessible only to you (admin / dev). The user does not need to know the reason or where such errors occur. Of course it would be very useful to say something like " This feature has an error " but without detail ...
Another typical example is the connection to the PHP database via PDO which displays the data explicitly when they are not in a block try
/ catch
appropriate:
I used PHP as a reference, but the theory is equivalent in major programming languages. Maybe there are some minor differences ...