Errors occur in programs all the time. Some of these errors are undesirable and cause problems that should not be shown to the end user (client). This article covers supressing these errors as well as signalling errors in code.
Try...Catch
The most common style in programming of supressing an error is the Try...Catch statement.
PHP is no exception to this and when dealing with exceptions in PHP this statement may be used to collect errors.
Try...Catch has a simple structure:
<?php try{ //If the code in here fails, it raises the catch part of the Try...Catch } catch(Exception $e){ //If an error occurs the catch statement is activated and the error is put on the screen echo $e->getMessage(); } ?>
This code sample shows how to construct a Try...Catch statement.
The following example shows precisely how it works in the real world, working with a file that may not be found and in turn would fire out an error:
<?php try{ file_get_contents("file.txt"); } catch(Exception $e){ echo $e->getMessage(); } ?>
Raising exceptions
When an exception appears, this is because an exception has been raised.
An exception can be raised at any point in a program and they are particularly useful when writing custom libraries that are being distributed because the end programmer can in turn find out what is wrong with their code.
In PHP, as with many C-family languages, an exception is raised using the throw
keyword.
The following example demonstrates this:
<?php throw new Exception("I am Error"); ?>
When this error now occurs, the PHP application must use the Try...Catch statement to 'catch' it and do something about it. The following example demonstrates a whole application doing this:
<?php try{ if(file_exists("file.txt")){ return file_get_contents("file.txt"); } else{ throw new Exception("File not found"); } } catch(Exception $e){ echo $e->getMessage(); } ?>