1

A lot of tutorials and books I have been over and read have used the die() method to catch an exception when interacting with a local MySQL database

For example:

mysql_connect($dbhost, $dbuser, $dbpass)or die(mysql_error());

Would a try/catch block be more beneficial over the die() method or is that just the standard way that exception handling works with db connections?

AnonDCX
  • 2,501
  • 2
  • 17
  • 25
  • when you use *try/catch* you will use **throw new Exception()** instead of *die()* – donald123 Aug 24 '15 at 08:22
  • `try/catch` allows you to handle Exceptions cleanly, whereas `die()` is abrupt and rarely allows you to display user-friendly messages..... but `mysql_connect` doesn't throw any Exception, and the `MySQL_*` functiond are deprecated and won't exist in PHP for much longer – Mark Baker Aug 24 '15 at 08:22
  • No, you can write your way to handle this exception as you like (http://stackoverflow.com/a/9836727/3615630) – Mohammad Alabed Aug 24 '15 at 08:22
  • use die in development. How would you like die if you were booking a flight on Travelocity ? Also, why in the world are you using mysql_* functions? It is the 21st century :> – Drew Aug 24 '15 at 08:22
  • Die quits the application at whatever point it was called. Don't do this in production, use the try catch and return a nice pretty error message so your users won't be left with a blank page or some cryptic php error message. Also, `mysql_*` functions have been depricated as of php 5.5.0, use `mysqli_*` or `pdo` instead. – Pavlin Aug 24 '15 at 08:26
  • 1
    Correction: a lot of **bad** tutorials and books use `die()`. It's not the job of the code that connects to the database to decide when the application ends or how it reacts when the database is not accessible. Forget about `die()`, you don't need it. The place where the function [`exit()`](http://php.net/manual/en/function.exit.php) (the real name of `die()`) is needed is just after `header('Location:');` if you don't use a framework and handle these things manually. Apart from that, the usage of `exit()` is a code smell. – axiac Aug 24 '15 at 09:18

2 Answers2

0

The mysql_connect method does not throw exceptions and thus die() is used by many applications to terminate when there is no connection available. You can use the solution mentioned here: how to use throw exception in mysql database connect

Included for completeness:

try
{
    if ($db = mysqli_connect($hostname_db, $username_db, $password_db))
    {
        //do something
    }
    else
    {
        throw new Exception('Unable to connect');
    }
}
catch(Exception $e)
{
    echo $e->getMessage();
}

Alternatively use the new and more OOP styled database access: http://php.net/manual/en/book.pdo.php

The reason a lot of applications uses die is from the fact that they are so reliant on the database that continuing without a connection is utterly fruitless.

Edit As mentioned in the comments, the code example above is for illustrational purposes. Catching right after throwing is pointless.

Community
  • 1
  • 1
CodeTower
  • 6,293
  • 5
  • 30
  • 54
  • 1
    This is also sample code at best, just like `or die()`, since you'd never `try..catch` an exception immediately this way. – deceze Aug 24 '15 at 08:51
  • 2
    *"and thus die() is needed"* - No, `die()` it's not needed. It's not the responsibility of the code that connects to the database to decide how the application should behave when the database is not accessible. – axiac Aug 24 '15 at 09:13
0

or die() is an extremely primitive way to "handle" errors and only for examples or debugging at best. In practice, it depends on how you handle your errors. You may want to return false from a function call or you may want to throw your own exception instead; e.g.:

if (!$con = mysql_connect(..)) {
    throw new DatabaseConnectionError(mysql_error());
}

try..catch will do exactly nothing with mysql, since mysql never throws any exceptions. It only ever returns false on failure.

You will have to have your own error handling strategy. You'll probably want to log errors and display a user friendly error page instead of cryptic error messages. mysql is not concerned with that part. It only gives you a way to check whether an operation was successful or not (check if it returns false); what you do with this information is up to you. die kills the entire application and at least doesn't allow the problem to propagate further; but it certainly does not display any user friendly error pages.

Having said all this, mysql is old and deprecated. If you'd use something newer like PDO instead, it can properly throw exceptions itself.

deceze
  • 510,633
  • 85
  • 743
  • 889