해외축구중계스포츠중계축구중계EPL중계스포츠무료중계실시간스포츠
{"id":778,"date":"2018-02-16T06:54:10","date_gmt":"2018-02-16T06:54:10","guid":{"rendered":"https:\/\/www.wdb24.com\/?p=778"},"modified":"2018-04-22T19:58:03","modified_gmt":"2018-04-22T19:58:03","slug":"php-try-catch-tutorial-example","status":"publish","type":"post","link":"https:\/\/www.wdb24.com\/php-try-catch-tutorial-example\/","title":{"rendered":"PHP Try and Catch Tutorial with Example"},"content":{"rendered":"

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>.
\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>\n

Try and Catch Syntax:<\/h2>\n

<\/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 $e<\/code>.<\/p>\n

Exception object has following method.<\/p>\n\n\n\n\n\n\n\n\n\n\n
Method<\/strong><\/th>\n Description<\/strong><\/th>\n<\/tr>\n
getMessage()<\/td>\n Get exception message<\/td>\n<\/tr>\n
getCode()<\/td>\n Get the numeric exception code<\/td>\n<\/tr>\n
getFile()<\/td>\n Gets the file in which the exception was created<\/td>\n<\/tr>\n
getLine()<\/td>\nGet the line number where the exception occurred<\/td>\n<\/tr>\n
getTrace()<\/td>\n Get the backtrace before the exception<\/td>\n<\/tr>\n
getPrevious()<\/td>\n Displays the previous exception<\/td>\n<\/tr>\n
getTraceAsString()<\/td>\n Get the backtrace of the exception as a string instead of an array<\/td>\n<\/tr>\n
__toString()<\/td>\n String representation of the exception<\/td>\n<\/tr>\n<\/table>\n

Try and Catch Basic Example:<\/h3>\n

Below is the simple example in which we have 2 variable $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<\/ins>
\n