Note:

If you want to create a new page for developers, you should create it on the Moodle Developer Resource site.

Exceptions

From MoodleDocs

Moodle 2.0

Exceptions are a common feature in all modern programming languages. They help us to handle exceptional problems that may appear unexpectedly during code execution.

Overview

Please keep in mind that exceptions are for something really exceptional, normal code execution flow should not depend on them.

Examples of suitable use are:

  • problem writing to directory moodledata directory - this is expected to be always writable
  • wrong function/method parameters - coding error which must be fixed by a developer
  • inserting data into non-existent database table

Incorrect uses:

  • using exceptions instead of break in order to terminate loops
  • returning results from functions

Major benefits

Less code

Many IFs can be eliminated.

Return values are not mixed with error flags

In previous versions database functions were returning false if something went wrong during execution. Sometimes the false value also meant no value found.

Recovery after error

Previously if something went wrong we either returned false and printed debug info or terminated execution with error(), print_error() or die(). Exceptions allow us to wrap potentially problematic code in try-catch block and recover from exceptions.

Example of suitable use could be admin/cron.php. There were several problems with module scripts terminating and preventing execution of other parts of cron script. Now we can wrap all calls to cron functions in try-catch block and recover from problems in individual activities or 3rd party code.

Exception hierarchy

Exceptions.png

See also