PHP understanding exceptions

I’m trying to understand exception handling in PHP and cant quite get it. I read every post, article and comment i could find, but cant seem to figure it out.

What i don’t understand is:

1. Why use exceptions?
Exceptions allow you to catch errors, if you think/know that an error could occur in a specific location in your code, then you can throw an exception and catch it.
What i don’t understand is why not set up the code to NOT be able to have an error in the first place? It kind of seems to me like using exceptions for handling these kinds of errors is in a way ignoring the problem, if you know that this piece of code could have an error, why not change it so that it cant have an error?

2. How to use exceptions?
Obviously i’m not understanding exceptions very well, but i do understand that its best practice(?), so how should exceptions be used?

Should a try/catch be wrapped around specific lines of code like this:

function doSomething(){
    try{
        if($var == "value"){
            echo 'good';
        }else{
            throw new Exception();
        }
    }catch(Exception $e) {
        echo 'bad';
    }
    try{
        if($var2 == "value2"){
            echo 'still good';
        }else{
            throw new Exception();
        }
    }catch(Exception $e) {
        echo 'bad';
    }
}

doSomething();

or should they be wrapped around the actual function to catch multiple exceptions like this:

function doSomething(){
    if($var == "value"){
        echo 'good';
    }else{
        throw new Exception();
    }

    if($var2 == "value2"){
        echo 'still good';
    }else{
        throw new Exception();
    }
}

try{
    doSomething();
}catch(Exception $e) {
    echo 'bad';
}

Can i wrap functions and classes in a try/catch, and if that function/class throws an exception catch it, or should each line that could throw an exception have the try/catch around it?

3. What counts as an exception?
If a user gets to a page they are not supposed to be on, for example a logged in user gets to the login page, i want to redirect that user to the home page, is that an exception?

Another example:
If a user submits a form and the form is corrupt in someway (not necessarily because of the code, maybe someone tried to hack the form, altered the form through the inspect element, etc.), i want to send the user back to the form, log the event, and show the user a general message, is this an exception?

4. Logging exceptions and showing users alerts
For some exceptions, like the form example above, i want to log the event and let the user know that something happened. For other exceptions i don’t.
I know there can be multiple exception classes inheriting from the main Exception() class, but is this best practice, or is having one general class for exception handling best?

So this is king, He’s once again my guest…:grinning:

  1. Due “clean code” or “high development style”.

  2. No common rule. Depends of your code.

3.1 Yes. You should to warn user that something wrong.
3.2 No, except of CSRF-token. You can’t to know why form data is not valid.

  1. Lot of classes. Common rule: any class or even method should to have its own specific mission.

A programmer friend of mine allegedly read an article that recommended assuming user input was always correct and by not validating the script was a lot faster. This would be an ideal case for using exception handling :slight_smile:

Perhaps checking error logs would also show where existing script had failed and could be trapped by using exception handling.

I check all user input with my FormHandler class, this class validates the form (checks if its corrupt) and the inputs. If there is an error with an input, it saves it in the session.
This though is also a point that i’m questioning, when its user input, i want to just show them a message. When its another issue with the form, this i assume should be an exception. Should it be a custom exception?

Should i have custom exceptions for each kind of error, e.g. FormException, DatabaseException, etc…?

I have an ErrorHandler class also, this class saves and emails all of the errors that occur in php, syntax errors and things that that. Not exceptions or user input or anything like that.

Yes i have read that in a few places, but i still don’t understand why if you know there could be an error in a specific code, why would you allow it to exist rather than fix it, or simply putting an if statement to check if its actually what you expect it to be, if its not then do something else. In this case i don’t understand why one would choose to allow an error to occur and to catch it, rather than to just fix it from the start.

In that case i would wrap my functions that i “think” could cause an error or not work as its supposed to in a try/catch, and in the function i would throw the exceptions?

In most cases i want to warn the user that something is wrong, this is also something that i am not sure of how to do as this is something that i havent found in posts or articles.
Should i save exception messages in the session to output to the users (not the actual error, but a general “there was a problem” message)?

There should be many classes for exception handling?
How does this look in reality, is there an exception for forms, and exception for database, and exception for being on the wrong page, one for general function failures?

Yes i have read that in a few places, but i still don’t understand why if you know there could be an error in a specific code, why would you allow it to exist rather than fix it, or simply putting an if statement to check if its actually what you expect it to be, if its not then do something else. In this case i don’t understand why one would choose to allow an error to occur and to catch it, rather than to just fix it from the start.

“Clean code” means also maximum independency of any code part. Doesn’t known where an error was created and where and how it should be handled. With exception your class just says: Something wrong.

Should i save exception messages in the session to output to the users (not the actual error, but a general “there was a problem” message)?

If you would.

There should be many classes for exception handling?

Yes. If you have a specific exception, better to use or write by yourself some specific class for it.

How does this look in reality, is there an exception for forms, and exception for database, and exception for being on the wrong page, one for general function failures?

Depends of your code. E.g. in incorrect SQL you need exception, that shows also SQL-query, SQL-error code, SQL-error message and query params. So create specific exception class for it.

I have an ErrorHandler class also, this class saves and emails all of the errors that occur in php, syntax errors and things that that. Not exceptions or user input or anything like that.

Try using Php 7 and declare(strict_types=1); because it will fail fast by showing all syntax errors.

Also explicitly set all function parameter types and function return types because this catches all sloppy script. PHP should also run a little faster by not having to “juggle types”.

It is not easy to make recommendations that apply to every case. Far better to post example scripts and request improvements.

Right, the class just says something is wrong, but why let it get to that point if you know there’s going to be something wrong? Why not just write the code in a way that there wont be something wrong? (I’m referring to coding errors here, and not user input).

How would this be set up then? i haven’t seen any examples that implement the set_exception_handler() and multiple exceptions like CustomException1, CustomException2, etc.

Would i even use set_exception_handler() or would i just say create a folder that has files and each file has a specific exception class in it that extends the base Exception?

Another point is that in all of the examples that i have seen where the Exception class is extended to custom classes, like RegistrationException, FormException, etc., those classes are actually empty and nothing goes in them.

This really confuses me as i thought that the whole point of extending Exception and using custom classes is to do custom functions, but in all cases i have seen, these extended classes are empty.

If nothing actually goes in to the custom exceptions, what is the point of them? :thinking:

Why not just write the code in a way that there wont be something wrong?

Because that is impossible by complex systems.

How would this be set up then?

E-e… I don’t understand the problem. In some exception case you use one exception class, in other case - another class.

This really confuses me as i thought that the whole point of extending Exception and using custom classes is to do custom functions, but in all cases i have seen, these extended classes are empty.
If nothing actually goes in to the custom exceptions, what is the point of them?

If GI promoted from private 1 to private 2, no third hand grows by him up.:grinning:

If you catch exception, you could to undestand, why it was thrown, by exception’s class.

Right, i could understand that if the class actually had anything in it, but the classes are empty, they dont log or do anything.

Is it just to see the class name when we look at the code? Or do the different classes actually do something?

Makes sense :sweat_smile:

By how to set it up i mean, do we use set_exception_handler() and custom classes, or just one class defined by set_exception_handler()?

Are you sure they aren’t there to prevent the problems from stopping the script? eg. “If something unexpected goes wrong, don’t bother doing anything about it, fail silently and continue” i.e. a kind of “error suppression”.

I’m not sure about anything at this point :sweat_smile:

I’m just trying to understand how to implement exception handling in to my app.

I understand that different exceptions should be used, its not very clear yet why though, because all of the tutorials and examples that i have seen that implement multiple extended exceptions, all of the custom classes are empty, so i don’t understand their actual purpose.

Plus, not sure if set_exception_handler() should be used or not, and how to use it along with the custom exception handlers.

Nice idea in a perfect world of peffect programmers and perfect servers.

For one, the error may not even be in your code, it could be the server is having a bad day, over loaded, under attack or in maintenence, it may be a file is not retreived or a database connection fails. It happens.

And for coding errors, of course you thoroughly test and fully debug your code before uploading to the live server believing it to be complete. But you have accept that the possibility exists that there is some scenario you never thought of during testing and just maybe there could be a bug in there that you never spotted during testing. It happens. Never assume your code is perfect and bug free just because you tested it and saw no error.

In either case, when it does happen you want firstly for it to be handled as gracefully as possible on the client side and secondly you want it logged and to be allerted of the problem.

1 Like

Yes i understand that, i have an ErrorHandler class handling errors that occur in php.
I am now working on writing an exception handler to handle the unexpected/expected and am having a hard time figuring out how exception handling is supposed to work and how to implement it.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.