COM372: Notes, Chapter 7

Exception Handling
pages 191-201

Syllabus | Grading | Reading Notes | Dr. Logan

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

User-built exception classes overcome the final (can't be overridden) public methods (see listing 7.2, pages 194-195) of the built-in class. This is illustrated in listing 7.3 (pages 195-196). Further, albeit simple, illustration in listing 7.4 demonstrated creation of file input/output exceptions, which are then used in an example, listing 7.5, to handle problems arising when a file cannot be opened, a lock cannot be obtained, or the file cannot be written to (pages 197-200). Additional material is covered in chapter 25. (more on exceptions)