Exceptions and Their Uses

by Diya Yang


    Exceptions

    When using php, and you do something wrong(wrong password, wrong e-mail, etc), it is likely that it will give an system error, and when your website is up and running, those system errors will make users feel annoyed. Exceptions allow you to solve this problem by checking for the specific problem and, if the problem happens, shows a message that is more understandable to the users.

    What are They Used For?

    Exceptions are used similar to if...else... statements, and can be used the same way, however, sometimes languages do not support the if...else... statements, and that's when exceptions are especially important.

    How to code exceptions

    Exceptions are generally a 3-step code, first you must use try code to try for an exception, and if an exception is seen, it will be "thrown", and then another part of the code will "catch" the exception and determine what actions will be taken due to the exception. A example code of exception would be like this:
    <?php	
    	function checkNum($number)
      		if($number<5)
        	{
        	throw new Exception("Value must be 5 or above");
        	}
      	return true;
      	}
    	try
    		{
    		checkNum(2);
    		echo 'if you see this the number above 5';
    		}
    	catch (Exception $n)
    		{
    		echo 'Message:'.$n->getMessage();
    		}
    ?>
    If you use that code and then run it, then this will be returned:
      Message: Value must be 5 or above
    The reason is that you checked the number 2 for using the checkNum function, but the function throws a new exception if the number you check is below 5, we then use the catch function to "catch" the exception, meaning that if the exception exists, then a string message shows.You must always have a catch function if you coded to throw an exception, if you don't, then you would receive an error called uncaught exception meaning that an exception was thrown, but the code does not to know what to do with it.

    Refer to W3Schools for more complex type of exceptions.