Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
communitycreator

How to perform error handling in PHP with the die() function

NDUKWE CHIDERA K.

In PHP, some errors will cause the script to stop executing and terminate the program due to a user’s action. Such errors tend to throw very detailed and technical messages, which are not required by the user.

Warning: fopen(error_handle.txt) [function.fopen]: failed to open stream: No such file or directory in C:\mypc\errors.php on line 12

Error messages like the one above will be most useful for the programmer and not the user. You can use several built-in functions in PHP, including the die() function, to avoid such situations.

The die() function

The die() function is an alias of the exit() function. The functions basically do the same thing, which is to terminate a script at the point they are called.

Syntax

die(message)

die() takes a single required parameter, which is the message to be printed out to the screen upon encountering the error.

Code

In the example below, I have a simple file reader code snippet that opens and reads a specified file.

If the specified file is not found, the error message passed to the die() function is displayed.

<?php

if(!file_exists("error_handle.txt")) {
die("specified file, missing");
} else {
  $file=fopen("error_handle.txt","r");
}

?>

Pros and cons of the die() function

Pros

  • Offers very simple off-the-shelf error handling ability to the programmer.
  • die() lets you display messages in your own words.

Cons

  • This error handling method is seen as very disruptive and crude because it breaks your entire program when called.
  • Users don’t really find die() appealing, as they wish to keep using the program even in the face of some minor fails that aren’t really critical.

Conclusion

  • Only use the die() function in critical cases, like when your database connection fails, the script should obviously terminate, or when the lack of success of such operations defeats the aim of the program.
  • You can use custom error handling methods, which catch errors, display messages, and don’t break your code, to make your program run much smoother.

RELATED TAGS

php
communitycreator
RELATED COURSES

View all Courses

Keep Exploring