COM372: Notes, Chapter 7
Exception Handling
pages 191-201
Exception Handling
Concepts: If running your code produces an error, you don't want your program to simply stop running. Exception handling provides a structure (a language construct, not a function), which you must build, to do something other than displaying a blue screen-of-death. The code that you want to run can be run in a try block; if something goes wrong (an exception), execution is transferred (thrown) to a code block (within the try block), marked by the keyword throw. Syntax is throw new Exception (str_message, code);. Right below the try block, you also write one or more catch blocks; these are passed an object by the throw code. Usually, this object is derived from the PHP built-in exception class. Here is the complete code structure (page 192):
<?php
try
{
throw new Exception ('OMG: You gotta do SOMETHING!', 22);
}
catch (Exception $code)
{
echo 'Exception '. $e-->getCode(). ': '. $e->getMessage() .' in '.$e->getFile(). ' on line'. $e-getline(). '<br />';
}
?>
The Exception Class: The Exception class has two parameters, a message and a code. It also has methods
- getCode()—returns the error code as passed to the constructor getMessage()—returns the message as passed to the constructor
- getFile()—returns the full path to the code file where the exception was raised
- getLine()—returns the line number in the code file where the exception was raised
- getTrace()—returns an array containing a backtrace (shows which functions were executing when the exception was raised) where the exception was raised
- getTraceAsString()—returns the same information as getTrace, formatted as a string
- __toString()—allows a simple echo of an exception object, giving all the information from the above methods