Search code examples
phptry-catchcustom-exceptions

Is it bad programming to just throw exceptions while not in a try catch block?


I'm currently working in PHP. I'm working on a error system for my CMS I'm building (for the fun of it). For fatal errors in my system (not in the php compiler) I created a FatalException class that extends the built in Exception class. Since these types of errors kinda halt the system anyway, I threw in a exit into the __construct.

    class FatalException extends Exception{  
        public function __construct($message) {
            exit("<h1 style='color:red;' >FATAL ERROR: $message </h1>");
        }
    }

So in my code I'll check something like the connection to the database and if it can't then I'll just throw a FatalException("Can't connect to database: $database_error_message"). It won't be in a try/catch block.

When I run the code and can't connect to the database, for example, all I see on the screen is a sentence in big red letters. So it works just fine, but is this bad practice/coding?

EDIT:

Actually in truth it didn't start out this way. I was originally logging the error and then exiting in the catch area, but then I thought, if all fatal errors are going to exit anyway then just put in the in constructor. Then I noticed it wasn't actually getting to the catch area it was exiting. So putting the statement in a try/catch block was kind of a moot point. Which lead to the question.


Solution

  • Even you wrap exit() into a member function of an exception, you are not using the exception here for error handling, but just the exit() - the exception is never thrown, PHP comes to halt before that happens.

    So it works just fine, but is this bad practice/coding?

    Yes, it is bad practice. It also works just fine if you would have created yourself a function:

    function error_exit($message) {
        exit("<h1 style='color:red;' >FATAL ERROR: $message </h1>");
    }
    

    Instead think about whether you want to use Excpetions or you want to exit().