<?php
function some_function($arg) {
if($filter->check_for_safe_input($arg)) {
throw new Exception("Hacking Attempt");
}
do_some_database_stuff($arg);
}
?>
In the above code example, does do_some_database_stuff ever get called if check_for_safe_input fails, or does the exception stop the function running? It's something I've never quite been sure of, and usually I just stick functions like do_some_database_stuff in an else statement to be sure, but this tends to lead to hugely nested functions.
Yes, uncaught exceptions result in fatal errors that stop the execution of the script. So the do_some_database_stuff function will not be called if an exception is thrown. You can read more about exceptions in this article.
Have a look at the PHP manual on exceptions.
When an exception is thrown, code
following the statement will not be
executed, and PHP will attempt to find
the first matching catch block. If an
exception is not caught, a PHP Fatal
Error will be issued with an "Uncaught
Exception ..." message, unless a
handler has been defined with
set_exception_handler().
php.net/exceptions
So yes, the rest of the function is not being executed, a fatal error occurs instead.
If you catch the exception, execution of the script continues in the corresponding catch block, everything "between" the function which throws an exception and the catch block is not executed.
An exception, if not catched, will end script execution.
See the PHP manual chapter on Exceptions
Related
I am a bit confused about those terms and their exact meaning / handling in PHP:
Exception could be defined like this:
When an error occurs within a method, the method creates an object and
hands it off to the runtime system. The object, called an exception
object, contains information about the error, including its type and
the state of the program when the error occurred. Creating an
exception object and handing it to the runtime system is called
throwing an exception.
Exceptions can be caught and handled.
Fatal Error could be defined like this:
Fatal errors are critical errors - for example, instantiating an
object of a non-existent class, or calling a non-existent function.
These errors cause the immediate termination of the script, and PHP's
default behavior is to display them to the user when they take place.
Fatal errors can not necessarily be caught (they do not throw usual exceptions), otherwise there would be no more specific Catchable Fatal Error.
However how is a Catchable Fatal Error different from a normal Exception? And is it handled the same? Is a catchable fatal error a specific type of exception or not?
Fatal errors can not necessarily be caught (they do not throw usual
exceptions)
Prior to version 7, this was the case. Fatal errors used to stop the script dead in its tracks. However, as of version 7, they're now presented as catchable exceptions. This allows you to gracefully recover from pretty significant issues.
However how is a Catchable Fatal Error different from a normal
Exception?
They both implement Throwable, but with different anchor classes:
Throwable
Error
ParseError
...
Exception
RuntimeException
...
And is it handled the same?
Yep, you can catch them, just like Exceptions.
Is a catchable fatal error a
specific type of exception or not?
Depends on your semantics. A catchable fatal error is an exception but it's not an Exception, if you get my meaning. You can differentiate like this;
// "traditional" exceptions
try {
throw new Foo();
} catch (Exception $e) {
}
// v7 catchable fatal errors
try {
$not_an_object->not_a_method();
} catch (Error $e) {
}
// both
try {
} catch (Throwable $e) {
}
Can you have a method throw any exceptions that occurs within it's method body? I want to automatically 'throw' any PDO related exceptions without always having to use 'try/catch' blocks within a function/method.
Example:
function testExcption($a..) throws PDOException{
// PDO related code here.
}
So can I 'throw' and exception at the function/method declaration level and without any try/catch blocks?
EDIT
I'm trying to avoid always having to write 'try/catch' because I only care for the PDO related exceptions that can occur within those functions/methods. I have lots of methods/functions and I'm tired of using 'try/catch' all the time for PDO error handling, and again I only care for the PDO exceptions in those functions/methods. Does that make sense?
EDIT
Is there a way to get PDO errors w/o try/catch blocks?
Maybe you are mixing things. Throwing exceptions is done without any try/catch statment. Throwing Exceptions is as easy as:
function nonsensefunc(){
throw new Exception('<Description of Error>');
}
On the other side, when calling you function, you have to use try/catch, you are catching them.
So what happens, when you do not catch the errors? The Exception is thrown a level higher and finally is printed out. Mostly it triggers an abort in PHP and stops the rest of the script.
So what is your expected behaviour? The only way of doing other thing as the default behaviour (printing the error and stopping) is to catch it.
I would like to know how throw works in PHP.
For example, does it act like a die() or exit()? How can I know what is done internally?
I am asking this because I saw Kohana using their $this->redirect() method with a throw to terminate the script execution instead of the traditional exit.
throw is not like exit or die at all. Throwing an exception does not automatically terminate the application, a thrown exception can be caught by the application. Only when an exception is not caught will the application be terminated.
try {
throw new Exception;
} catch (Exception $e) {
echo 'caught it';
}
echo 'not dead yet';
Exceptions are a mechanism to signal errors to higher up callers in a more flexible and rigorous manner than simple return false statements would allow. They are not comparable to a simple exit or die.
I don't know what Kohana does exactly, but throwing an exception instead of using a simple exit or die is an abuse of exceptions. Exceptions should be thrown in exceptional error circumstances only.
As already explained, you use throw to throw exceptions that can be caught "further up" in your application.
When you work with objects and object oriented programming you start coding every single object you make as a standalone object that you can give to someone else. The public methods of these are an API, and the phpdoc above each public method details what exceptions the class might throw under certain circumstances.
So, someone has created a standalone object that does something for you, like writing to a disk. You want to use this object, so you look at the docs and see it throws a PermissionsException when the object can't write to the disk because of a permissions issue.
In your code that uses this person's object, you now know that you should catch that exception, log it, and continue however you want your application to work given that circumstance (show a nice error to the user if it's via an AJAX call, for example).
So, knowing this, when you code your own objects, make descriptive exceptions for different circumstances that someone who you give your object to can use and respond to in their own applications.
Both die and exit you don't really want to use in production applications. They're useful for debugging when you do a var_dump() and then want to halt application execution straight afterwards or if you want to completely stop the script from running for some reason.
As for why your specific found piece of code does it this way, you should ask the developer if it isn't documented with good reasoning.
Using "throw" without try/catch will terminate the script with a "catchable fatal error". As far as I know there's no benefit in using "throw" this way. If you want to terminate a script you should use exit(), so you don't need to suppress the error message.
I have the following pseudo code
public function testSomething() {
// assert something
// assert something else
$this->setExpectedException(...);
// trigger my exception here
// do one last thing
}
The issue I see, code after the exception being triggered is never made. Is this correct?
This is just a general wondering here - if this is normal I will refactor my test to perform the try/catch directly and fail() the test if nothing is caught.
The code after the exception should not be made. Think of the setExpectedException as making the test into a try -- catch So the code after the exception is thrown will not be executed.
If you need to do/check things after the exception, you should catch it. Though one warning with your catch, be specific about what exception is being thrown. PHPUnit throws exceptions for failed tests and you could accidentally catch this exception which may result in your test falsely passing.
Update:
If the code that you are executing is cleaning up, consider also moving it into the tearDown method of the test.
I used to use this when I wanted to trigger errors in PHP, coming from a PHP4 background. Note I had my own set_error_handler() for handling these errors.
if ($error) {
trigger_error('Sorry, error has occured');
}
I can't remember where, but sometime ago someone told me I should be 'using exceptions'. As I'm re factoring a lot of my old code, I figured now is the time to get some good advice on my error handling implementation.
Now that I'm using PHP5 (and a bit smarter than I was when I wrote the older code), is my trigger_error() just an old way of doing things, and if so, what is the best way to handle errors in PHP5?
Yes, you may want to start looking into the PHP 5 exception model. Remember though that just because something is new doesn't mean that you must adopt it. Only adopt those features that you need and make sense in your domain.
That being said, I feel that exceptions are a good concept to grasp and even if you decide not to adopt them you will be all the better for the experience.
I would like to suggest that you read PHP: Exceptions - Manual:
PHP 5 has an exception model similar
to that of other programming
languages. An exception can be thrown,
and caught ("catched") within PHP.
Code may be surrounded in a try block,
to facilitate the catching of
potential exceptions. Each try must
have at least one corresponding catch
block. Multiple catch blocks can be
used to catch different classes of
exeptions. Normal execution (when no
exception is thrown within the try
block, or when a catch matching the
thrown exception's class is not
present) will continue after that last
catch block defined in sequence.
Exceptions can be thrown (or
re-thrown) within a catch block.
I would also encourage you to read What Is an Exception? (Note this is a Java tutorial but the concepts are universal)
When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.
Edit: In order to implement a global exception handler (basically in order to establish a default exception handler that will handle previously unhandled exceptions) you will want to us the set_exception_handler function.
Using exceptions is the object-oriented way to trigger and handle your own application errors.
The PHP manual topic on exceptions is probably a good place to start.
Here is a small example:
function doSomething() {
if ($error) {
throw new Exception('Some descriptive error message.');
}
}
try {
doSomething();
}
catch (Exception $e) {
die('<p class="error">' . $e->getMessage() . '</p>');
}