Exception Handling

Exception handling is carried out by the use of the keywords throw, trycatch.


An exception can be thrown and caught (catched).


  • Code may be surrounded in a try block, to facilitate the catching of potential exceptions
  • Each try must have at least one corresponding catch block
  • Multiple catch blocks can be used to catch different classes of exceptions
  • Normal execution (when no exception is thrown within the try block, or when a catch matching the thrown exception's class is not present) will continue after that last catch block defined in sequence
  • Exceptions can be thrown (or re-thrown) within a catch block.


  • When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block
  • If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ..." message, unless a handler has been defined with set_exception_handler().
  • In PHP 5.5 and later, a finally block may also be specified after the catch blocks
  • Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes.
  • The thrown object must be an instance of the Exception class or a subclass of Exception. Trying to throw an object that is not will result in a PHP Fatal Error.
	//create function with an exception
	function checkNum($number) {
		if($number>1) {
			throw new Exception("Value must be 1 or below");
		return true;

	//trigger exception in a "try" block
	try {
		//If the exception is thrown, this text will not be shown
		echo 'If you see this, the number is 1 or below';

	//catch exception
	catch(Exception $e){
		echo 'Message: ' .$e->getMessage();

Save & refresh browser:

If you see this, the number is 1 or below

Leave a Reply