{"id":1007,"date":"2021-04-10T09:05:03","date_gmt":"2021-04-10T09:05:03","guid":{"rendered":"https:\/\/phptutorial.net\/?page_id=1007"},"modified":"2021-05-21T13:06:45","modified_gmt":"2021-05-21T13:06:45","slug":"php-try-catch","status":"publish","type":"page","link":"https:\/\/www.phptutorial.net\/php-oop\/php-try-catch\/","title":{"rendered":"PHP try&#8230;catch"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you will learn how to use the PHP <code>try...catch<\/code> statement to handle exceptions.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='introduction-to-the-php-try-catch-statement'>Introduction to the PHP try&#8230;catch statement <a href=\"#introduction-to-the-php-try-catch-statement\" class=\"anchor\" id=\"introduction-to-the-php-try-catch-statement\" title=\"Anchor for Introduction to the PHP try...catch statement\">#<\/a><\/h2>\n\n\n\n<p>In programming, unexpected errors are called exceptions. Exceptions can be attempting to read a <a href=\"https:\/\/phptutorial.net\/php-tutorial\/php-file-exists\/\">file that doesn&#8217;t exist<\/a> or <a href=\"https:\/\/phptutorial.net\/php-pdo\/pdo-connecting-to-mysql\/\">connecting to the database server<\/a> that is currently down.<\/p>\n\n\n\n<p>Instead of halting the script, you can handle the exceptions gracefully. This is known exception handling.<\/p>\n\n\n\n<p>To handle the exceptions, you use the <code>try...catch<\/code> statement. Here&#8217;s a typical syntax of the <code>try...catch<\/code> statement:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"HTML, XML\" data-shcb-language-slug=\"xml\"><span><code class=\"hljs language-xml\"><span class=\"php\"><span class=\"hljs-meta\">&lt;?php<\/span>\n\n<span class=\"hljs-keyword\">try<\/span> {\n\t<span class=\"hljs-comment\">\/\/ perform some task<\/span>\n} <span class=\"hljs-keyword\">catch<\/span> (<span class=\"hljs-keyword\">Exception<\/span> $ex) {\n\t<span class=\"hljs-comment\">\/\/ jump to this part<\/span>\n\t<span class=\"hljs-comment\">\/\/ if an exception occurred<\/span>\n}\n<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">HTML, XML<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">xml<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this syntax, the <code>try...catch<\/code> statement has two blocks: <code>try<\/code> and <code>catch<\/code>.<\/p>\n\n\n\n<p>In the <code>try<\/code> block, you do some tasks e.g.,reading a file. If an exception occurs, the execution jumps to the <code>catch<\/code> block.<\/p>\n\n\n\n<p>In the <code>catch<\/code> block, you specify the exception name and the code to handle a specific exception.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='php-try-catch-example'>PHP try&#8230;catch example <a href=\"#php-try-catch-example\" class=\"anchor\" id=\"php-try-catch-example\" title=\"Anchor for PHP try...catch example\">#<\/a><\/h2>\n\n\n\n<p>The following example shows how to read data from a CSV file:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"HTML, XML\" data-shcb-language-slug=\"xml\"><span><code class=\"hljs language-xml\"><span class=\"php\"><span class=\"hljs-meta\">&lt;?php<\/span>\n\n$data = &#91;];\n\n$f = fopen(<span class=\"hljs-string\">'data.csv'<\/span>, <span class=\"hljs-string\">'r'<\/span>);\n\n<span class=\"hljs-keyword\">do<\/span> {\n\t$row = fgetcsv($f);\n\t$data&#91;] = $row;\n} <span class=\"hljs-keyword\">while<\/span> ($row);\n\nfclose($f);<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">HTML, XML<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">xml<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>If the <code>data.csv<\/code> file doesn&#8217;t exist, you&#8217;ll get many warrnings. The following shows the first warning:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">PHP Warning:  fopen(data.csv): failed to open stream: No such file or directory in ... on line 5<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">plaintext<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">plaintext<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>To fix this, you may add an <a href=\"https:\/\/phptutorial.net\/php-tutorial\/php-if\/\"><code>if<\/code> statement<\/a> in every step:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"HTML, XML\" data-shcb-language-slug=\"xml\"><span><code class=\"hljs language-xml\">\n<span class=\"php\"><span class=\"hljs-meta\">&lt;?php<\/span>\n\n$data = &#91;];\n\n$f = fopen(<span class=\"hljs-string\">'data1.csv'<\/span>, <span class=\"hljs-string\">'r'<\/span>);\n\n<span class=\"hljs-keyword\">if<\/span> (!$f) {\n\t<span class=\"hljs-keyword\">echo<\/span> <span class=\"hljs-string\">'The file is not accessible.'<\/span>;\n\t<span class=\"hljs-keyword\">exit<\/span>;\n}\n\n<span class=\"hljs-keyword\">do<\/span> {\n\t$row = fgetcsv($f);\n\t<span class=\"hljs-keyword\">if<\/span> ($row === <span class=\"hljs-keyword\">null<\/span>) {\n\t\t<span class=\"hljs-keyword\">echo<\/span> <span class=\"hljs-string\">'The stream is invalid.'<\/span>;\n\t\t<span class=\"hljs-keyword\">exit<\/span>;\n\t}\n\n\t<span class=\"hljs-keyword\">if<\/span> ($row === <span class=\"hljs-keyword\">false<\/span>) {\n\t\t<span class=\"hljs-keyword\">echo<\/span> <span class=\"hljs-string\">'Other errors occurred.'<\/span>;\n\t\t<span class=\"hljs-keyword\">exit<\/span>;\n\t}\n\n\t$data&#91;] = $row;\n} <span class=\"hljs-keyword\">while<\/span> ($row);\n\n<span class=\"hljs-comment\">\/\/ close the file<\/span>\n<span class=\"hljs-keyword\">if<\/span> (!$f) {\n\tfclose($f);\n}\n\nprint_r($data);<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">HTML, XML<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">xml<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>However, this code mixes the program logic and error handlers.<\/p>\n\n\n\n<p>The advantage of the <code>try...catch<\/code> statement is to separate the program logic from the error handlers. Therefore, it makes code easier to follow.<\/p>\n\n\n\n<p>The following illustrates how to use the <code>try...catch<\/code> block for reading data from a CSV file:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"HTML, XML\" data-shcb-language-slug=\"xml\"><span><code class=\"hljs language-xml\"><span class=\"php\"><span class=\"hljs-meta\">&lt;?php<\/span>\n\n$data = &#91;];\n\n<span class=\"hljs-keyword\">try<\/span> {\n\t$f = fopen(<span class=\"hljs-string\">'data.csv'<\/span>, <span class=\"hljs-string\">'r'<\/span>);\n\n\t<span class=\"hljs-keyword\">do<\/span> {\n\t\t$row = fgetcsv($f);\n\t\t$data&#91;] = $row;\n\t} <span class=\"hljs-keyword\">while<\/span> ($row);\n\n\tfclose($f);\n} <span class=\"hljs-keyword\">catch<\/span> (<span class=\"hljs-keyword\">Exception<\/span> $ex) {\n\t<span class=\"hljs-keyword\">echo<\/span> $ex-&gt;getMessage();\n}\n<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">HTML, XML<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">xml<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this example, if any error occurs in the <code>try...block<\/code>, the execution jumps to the <code>catch<\/code> block.<\/p>\n\n\n\n<p>The exception variable <code>$ex<\/code> is an instance of the <code>Exception<\/code> class that contains the detailed information of the error. In this example, we get the detailed error message by calling the <code>getMessage()<\/code> method of the <code>$ex<\/code> object.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='multiple-catch-blocks'>Multiple catch blocks <a href=\"#multiple-catch-blocks\" class=\"anchor\" id=\"multiple-catch-blocks\" title=\"Anchor for Multiple catch blocks\">#<\/a><\/h2>\n\n\n\n<p>A <code>try...catch<\/code> statement can have multiple <code>catch<\/code> blocks. Each <code>catch<\/code> block will handle a specific exception:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"HTML, XML\" data-shcb-language-slug=\"xml\"><span><code class=\"hljs language-xml\"><span class=\"php\"><span class=\"hljs-meta\">&lt;?php<\/span>\n\n<span class=\"hljs-keyword\">try<\/span> {\n\t<span class=\"hljs-comment\">\/\/code...<\/span>\n} <span class=\"hljs-keyword\">catch<\/span> (Exception1 $ex1) {\n\t<span class=\"hljs-comment\">\/\/ handle exception 1<\/span>\n} <span class=\"hljs-keyword\">catch<\/span> (Exception2 $ex2) {\n\t<span class=\"hljs-comment\">\/\/ handle exception 2<\/span>\n} <span class=\"hljs-keyword\">catch<\/span> (Exception1 $ex3) {\n\t<span class=\"hljs-comment\">\/\/ handle exception 3<\/span>\n}\n...<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">HTML, XML<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">xml<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>When a <code>try...catch<\/code> statement has multiple <code>catch<\/code> blocks, the order of exception should be from the specific to generic. And the last <code>catch<\/code> block should contain the code for handling the most generic exception. By doing this, the <code>try...catch<\/code> statement can catch all the exceptions.<\/p>\n\n\n\n<p>If you have the same code that handles multiple types of exceptions, you can place multiple exceptions in one <code>catch<\/code> block and separate them by the pipe (<code>|<\/code>) character like this:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"HTML, XML\" data-shcb-language-slug=\"xml\"><span><code class=\"hljs language-xml\"><span class=\"php\"><span class=\"hljs-meta\">&lt;?php<\/span>\n\n<span class=\"hljs-keyword\">try<\/span> {\n\t<span class=\"hljs-comment\">\/\/code...<\/span>\n} <span class=\"hljs-keyword\">catch<\/span> (Exception1 | Exception2 $ex12) {\n\t<span class=\"hljs-comment\">\/\/ handle exception 1 &amp; 2<\/span>\n} <span class=\"hljs-keyword\">catch<\/span> (Exception3 $ex3) {\n\t<span class=\"hljs-comment\">\/\/ handle exception 3<\/span>\n}<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">HTML, XML<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">xml<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>By specifying multiple exceptions in the <code>catch<\/code> block, you can avoid code duplication. This feature has been supported since PHP 7.1.0.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='ignoring-the-exception-variable'>Ignoring the exception variable <a href=\"#ignoring-the-exception-variable\" class=\"anchor\" id=\"ignoring-the-exception-variable\" title=\"Anchor for Ignoring the exception variable\">#<\/a><\/h2>\n\n\n\n<p>As of PHP 8.0, the variable name for the caught exception is optional like this:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"HTML, XML\" data-shcb-language-slug=\"xml\"><span><code class=\"hljs language-xml\"><span class=\"php\"><span class=\"hljs-meta\">&lt;?php<\/span>\n\n<span class=\"hljs-keyword\">try<\/span> {\n\t<span class=\"hljs-comment\">\/\/code...<\/span>\n\n} <span class=\"hljs-keyword\">catch<\/span> (<span class=\"hljs-keyword\">Exception<\/span>) {\n\t<span class=\"hljs-comment\">\/\/ handle exception<\/span>\n}\n<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">HTML, XML<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">xml<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this case, the <code>catch<\/code> block will still execute but won&#8217;t have access the <code>Exception<\/code> object.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='summary'>Summary <a href=\"#summary\" class=\"anchor\" id=\"summary\" title=\"Anchor for Summary\">#<\/a><\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li>Use the <code>try...catch<\/code> statement to handle exceptions. <\/li><li>The <code>try...catch<\/code> statement separates the program logic and exception handlers.<\/li><li>Use multiple catch blocks to handle multiple exceptions. Place the most specific exception first and the least specific exception after.<\/li><li>Specify a list of pipe-separated exceptions in a single <code>catch<\/code> block if the same code can handle multiple exceptions.<\/li><li>Ignore the exception variable when you don&#8217;t want to access the detail of the exception.<\/li><\/ul>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Did you find this tutorial useful?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"1007\"\n\t\t\t\tdata-post-url=\"https:\/\/www.phptutorial.net\/php-oop\/php-try-catch\/\"\n\t\t\t\tdata-post-title=\"PHP try&#8230;catch\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"1007\"\n\t\t\t\tdata-post-url=\"https:\/\/www.phptutorial.net\/php-oop\/php-try-catch\/\"\n\t\t\t\tdata-post-title=\"PHP try&#8230;catch\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\n\t\t\t<button class=\"btn btn-primary wth-btn-submit\">Send<\/button>\n\t\t\t<button class=\"btn wth-btn-cancel\">Cancel<\/button>\n\t\t\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you will learn how to use the try&#8230;catch statement to handle exceptions that may occur in the script.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":1753,"menu_order":31,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-1007","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.phptutorial.net\/wp-json\/wp\/v2\/pages\/1007","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.phptutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.phptutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.phptutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.phptutorial.net\/wp-json\/wp\/v2\/comments?post=1007"}],"version-history":[{"count":3,"href":"https:\/\/www.phptutorial.net\/wp-json\/wp\/v2\/pages\/1007\/revisions"}],"predecessor-version":[{"id":1010,"href":"https:\/\/www.phptutorial.net\/wp-json\/wp\/v2\/pages\/1007\/revisions\/1010"}],"up":[{"embeddable":true,"href":"https:\/\/www.phptutorial.net\/wp-json\/wp\/v2\/pages\/1753"}],"wp:attachment":[{"href":"https:\/\/www.phptutorial.net\/wp-json\/wp\/v2\/media?parent=1007"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}