Errors are something which may occur anytime with in the php script. As a web developer I tried my best to write error free code. But error is something you cannot overcome.<\/p>\n
PHP<\/a> has built in error handling mechanism that will trigger on specific type. A list of these types are available on php site<\/a>. <\/p>\n Try block attempt to execute some code and if the code has error then try block raise an exception.<\/p>\n Catch block then catch the exception and assign that exception object to Exception object has following method.<\/p>\n Below is the simple example in which we have 2 variable
\nPHP also provide try and catch<\/strong> block to handle errors more sophistically. So in this tutorial I will discuss try and catch block with example.<\/p>\nTry and Catch Syntax:<\/h2>\n
$e<\/code>.<\/p>\n
\n
\n Method<\/strong><\/th>\n Description<\/strong><\/th>\n<\/tr>\n \n getMessage()<\/td>\n Get exception message<\/td>\n<\/tr>\n \n getCode()<\/td>\n Get the numeric exception code<\/td>\n<\/tr>\n \n getFile()<\/td>\n Gets the file in which the exception was created<\/td>\n<\/tr>\n \n getLine()<\/td>\n Get the line number where the exception occurred<\/td>\n<\/tr>\n \n getTrace()<\/td>\n Get the backtrace before the exception<\/td>\n<\/tr>\n \n getPrevious()<\/td>\n Displays the previous exception<\/td>\n<\/tr>\n \n getTraceAsString()<\/td>\n Get the backtrace of the exception as a string instead of an array<\/td>\n<\/tr>\n \n __toString()<\/td>\n String representation of the exception<\/td>\n<\/tr>\n<\/table>\n Try and Catch Basic Example:<\/h3>\n
$a<\/code> and
$b<\/code>. In try block there is a
$c<\/code> variable that holds quotient of
$a \/ $b<\/code>.
\nIf $c (quotient) is greater than 1 then it will throw an error. Right now $a has 10 value and $b has 9 value. So below code will throw an error. If you change $b value greater than or equal to 10 then it will print else block which is “Quotient is here”. But right now it will throw an error.<\/p>\n\r\n 1)\r\n {\r\n\t throw new Exception(\"Quotient is greater than one \");\r\n }\r\n else\r\n {\r\n\t echo \"Here is Quotient: \".$c;\r\n }\r\n\r\n}\r\ncatch(Exception $e)\r\n{\r\n echo \"Error : \".$e->getMessage();\r\n\t \r\n}\r\n?>\r\n<\/pre>\n
\n