PHP: Exceptions VS Errors

PHP: exceptions vs errors?

Exceptions are thrown - they are intended to be caught. Errors are generally unrecoverable. Lets say for instance - you have a block of code that will insert a row into a database. It is possible that this call fails (duplicate ID) - you will want to have a "Error" which in this case is an "Exception". When you are inserting these rows, you can do something like this

try {
$row->insert();
$inserted = true;
} catch (Exception $e) {
echo "There was an error inserting the row - ".$e->getMessage();
$inserted = false;
}

echo "Some more stuff";

Program execution will continue - because you 'caught' the exception. An exception will be treated as an error unless it is caught. It will allow you to continue program execution after it fails as well.

PHP: What is the difference between an exception and a catchable fatal error?

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) {
}

Difference between Error and ErrorException in PHP 7

You can catch purpose of Error class from this page which describes errors in php

PHP 7 changes how most errors are reported by PHP. Instead of
reporting errors through the traditional error reporting mechanism
used by PHP 5, most errors are now reported by throwing Error
exceptions.

The same description on its own Error page:

Error is the base class for all internal PHP errors.

So you shouldn't use this class for your user defined exceptions.

The purpose of ErrorException you can get from this good SO question/answers:

ErrorException is mostly used to convert php error (raised by
error_reporting) to Exception

But in php7 you don't need to convert php error to Exception.

So you basically should extend simple Exception or you can use for standard situations these predefined set of SPL Exceptions (e.g. InvalidArgumentException, OutOfBoundsException, BadFunctionCallException, ...)

Difference between exceptions and errors?

There is no "should" or "best" way to do error handling.

Generally speaking, there are two types of errors

  1. Those which are handled by other parts of the program. The user never sees or knows about these errors, at least not in a direct manner.
  2. Those which have caused enough failure that the user needs to be informed as such.

Notice that neither of these have anything to do with the specific PHP mechanisms you'd use to handle errors.

If you use exceptions...
Then I recommend using exceptions across the board. Register an exception handler and let it do most of the work - including other PHP errors. Invalid login details?

class InvalidLoginException extends Exception
{
protected $message = 'Login information is incorrect. Please try again.';
}

Then you have a bunch of choices for implementation.

try {
$user->login(); // will throw and InvalidLoginException if invalid
}
catch ( InvalidLoginException $e )
{
// display an error message
}

Or, if you so choose, let the exception handler do it. Maybe even in a more flexible way

class ApplicationErrorException extends Exception{}
class InvalidLoginException extends ApplicationErrorException
{
protected $message = 'Login information is incorrect. Please try again.';
}

Then, in the exception handler

if ( $exception instanceof ApplicationErrorException )
{
// dislpay error message
}

But exceptions aren't the only way, and by some not even considered a good way.

Are PHP exceptions really more useful than errors? (Adv)

I believe there is a philosophical difference between the definitions of errors and exceptions.

An error simply put is a programmed flaw, generated by a logical fallacy in the code. Passing strlen() an incorrect number of arguments should naturally be an error. An exception, on the other hand, handles those cases where everything is programmed correctly, but your code is interacting with resources outside of the codebase (filesystem, web service, external executable, etc). While it is expected that such external resources should work perfectly on every call, there will be cases -- out of the scope of your program's control -- that are not attributed to faults of your code (filesystem gets unmounted, connection timeout, etc). Because these issues are due to external factors, they are deemed exceptions.

The main difference is that an error occurs within one's own code, whereas an exception occurs in the case of an anomaly found in a third-party resource.

PHP Exceptions VS Return usage in Functions (best practice)

Years ago, when I read about it, I got a lot of information about the problem. First of all, the principle 'Tell, Don't Ask' (here and here) and after the entire Chapter 3 and 7 from Clean Code By Robert C. Martin.

With this, you can realize some good kinds of stuff to understand what the method should and shouldn't do.

A method should return only, and just only, when ask or asked for something. Methods asking something has the prefix as:

  • get; //mixed
  • has; //boolean
  • is; //boolean
  • can. //boolean

or, can has the word return (not necessary as prefix):

  • doSomethingAwesomeAndReturn. //mixed

The name create is an exception, because create not necessary has to return something:

  • createSomethingAwesomeAndReturn. //mixed

If your method doesn't have anything of this, it shouldn't return anything.

Inside the chapter 3, you can find the part called "Prefer Exceptions to Returning Error Codes" and inside chapter 7 you can find "Don’t Return Null". That explains about some problems created from returning something. A lot of validations chain, null object, etc... These problems can be solved just returning an exception.

Your second example is good, but like the method name says, it does awesome stuff, shouldn't return. If there isn't an exception, it did the awesome stuff. If the return is really necessary, you have to refactor or at least rename your method to match with is expected.

After all, it's just a lot of suggestion to guide your coding, not an inflexible rule.

Update

I've forgotten about the prefix add. It's an exception. A method prefixed as add should return the same object to match with the fluent interface, nothing else. As Fluent Interface at all, it shouldn't match with the above rules doesn't matter the name/prefix/suffix of the method, as it just made for be fluent, not to be cohesive.

error handling in php, die vs exceptions

I would like to save everyone some trouble and refer you to this stack here: PHP Error handling: die() Vs trigger_error() Vs throw Exception
Very detailed explanation of their uses, I believe it couldn't be said any better.

TypeError vs InvalidArgumentException?

TypeError is what mean the condition occurs when:

  1. argument type being passed to a function does not match its corresponding declared parameter type.
  2. Return type doesn't match with declared function return type.
  3. invalid number of arguments are passed to a built-in PHP function.

InvalidArgumentException is the exception thrown if an argument is not of the expected type.

Errors cannot be handled at runtime but exception can be handled at run time.

Is catching all PHP exceptions best practice?

As said on phpdelusions (https://phpdelusions.net/pdo#errors):

Despite a widespread delusion, you should never catch errors to report them. A module (like a database layer) should not report its errors. This function has to be delegated to an application-wide handler. All we need is to raise an error (in the form of exception) - which we already did. That's all. Nor should you "always wrap your PDO operations in a try/catch" like the most popular tutorial from tutsplus recommends. Quite contrary, catching an exception should be rather an exceptional case (pun intended).

In fact, there is nothing special in PDO exceptions - they are errors all the same. Thus, you have to treat them exactly the same way as other errors. If you had an error handler before, you shouldn't create a dedicated one for PDO. If you didn't care - it's all right too, as PHP is good with basic error handling and will conduct PDO exceptions all right.



Related Topics



Leave a reply



Submit