Hypertext Preprocessor ”PHP”,  is an open source programming language that is free to download and use. It is an extensively used language and PHP programs are run on the server.

PHP Error Handling Keywords

An error is an unanticipated program result that the program cannot handle. Errors are fixed by reinstalling the application. An infinite loop that never stops executing is an example of an error. 

What Is an Exception?

An exception is an unexpected software result that the program can manage. Attempting to open a file that does not exist is an example of an exception. This error can be handled by either generating the file or giving the user the option of searching for it.

Exception handling is a feature of PHP try and catch blocks, which contain the code to handle exceptions. They are crucial in the management of exceptions. 

Why Handle Exceptions?

  • Exceptions avoid having unexpected results on our site, which can be quite annoying to our visitors. 
  • To improve the security of our applications by avoiding disclosing information that could be used by hostile users to harm them. 
  • If a program's usual flow is disrupted by a predictable error, PHP exceptions are employed.

PHP Error Handling Keywords

Try catch: The try catch in PHP that may include an exception is contained in the try block.

Throw : The throw keyword is another crucial keyword in the try-catch block. Throw is a keyword that causes an exception to be thrown.

PHP Try Catch With Multiple Exception Types

The try catch in PHP that may include an exception is contained in the try block. The catch block catches an exception raised in the try block during runtime. As a result, at least one catch block is required for each try block. It is made up of the code block where an exception can arise. The following points concerning the attempt should be noted:

  • A catch or finally block must come after the try block.
  • With one attempt block, there can be numerous catch blocks.

Catch 

The try catch in PHP block raises an exception, which is caught in the catch. When a certain exception is thrown, the catch block is called. PHP looks for the catch block that matches the exception object, and assigns it to a variable.

The following are a few things to keep in mind about the catch:

  • With a try, there can be many catch blocks.
  • One or more catches catch the thrown exception and resolve it.
  • With a try block, the catch block is always used. It can't be utilized on its own.
  • It appears immediately after the attempt block.

Use of Try Catch- Finally

Try catch in PHP is a block that contains the program's vital code for execution. In PHP, the finally block is also used to clean up the code. The only difference is that it always runs regardless of whether or not an exception is thrown.

When to Use Try Catch-Finally

Use of Try catch-finally is useful in the following situations: database connection closure and stream.

Example 

<?php  

//user-defined function with an exception  

function testEven($num) {  

    //trigger an exception in a "try" block  

    try {  

         if($num%4 == 1) {  

           //throw an exception  

           throw new Exception("Passed number is an ODD Number");  

           echo "After throw this statement will not execute";  

          }  

          echo '</br> <b> If you see this text, the passed value is an EVEN Number </b>';  

     }  

     //catch exception  

     catch (Exception $e) {  

         echo '</br> <b> Exception Message: ' .$e->getMessage() .'</b>';  

     }  

     finally {  

        echo '</br> It is finally block, which always executes.';  

     }  

}  

      echo 'Output for ODD Number';  

      testEven(17);         

      echo '</br> </br>';  

      echo 'Output for EVEN Number';  

     testEven(11);  

?>  

Output

Try_Catch_in_PHP

Creating Custom PHP Exception Types

  • Apart from PHP exception class and its subclasses, we can also create our own custom exception classes to handle try catch in PHP exceptions.
  • With PHP 5.5 and above, finally block is used to handle exceptions. This block is always executed anyway, whether an exception is thrown or not.

How to Properly Log Exceptions in Your PHP Try Catch Blocks

Try catch in PHP introduces a new error model that allows you to throw and catch exceptions in your application, which is a far better way of dealing with mistakes than previous PHP versions. All exceptions are instances of the Exception base class, which we can modify to add our own custom exceptions.

It is vital to realize that exception handling and error handling are not the same thing. You will be able to control faults in this manner. However, some faults are unrecoverable and cause the software to stop working.

Exceptions, on the other hand, are intentionally thrown by the code and are meant to be detected at some point in your application. As a result, we can claim that exceptions are recoverable, whereas certain errors are not. If a thrown exception is caught someplace in your application, program execution resumes from where the exception was caught. And an exception that isn't caught anywhere in your application causes an error, which stops the program from running.

How to Use Try Catch With MySQL

To begin, it's important to note that though MySQL doesn't have classic try catch in PHP statements, it does provide conditions, which are similar to Exceptions. Both a code and a description are included in conditions.

You basically add a handler to your procedure instead of enclosing all of your code in a try catch block. In most cases, you'll wish to quit execution, which is handled by an exit handler in MySQL. When the handler is called, you may want to rollback or log the event, depending on the use case.

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Conclusion

This is all you need to know about the concept of try catch in PHP. If you want to learn more about the same or any other topic related to web development, programming or coding, you can enroll in Simplilearn’s Full Stack Web Development program and seek expertise in your subject to advance in your career and land better job opportunities.

Besides the varied specialization courses we provide, you can also sign up on SkillUp platform, a Simplilearn initiative where we offer numerous free online courses

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 15 Apr, 2024

6 Months$ 8,000
Full Stack Java Developer

Cohort Starts: 2 Apr, 2024

6 Months$ 1,449
Automation Test Engineer

Cohort Starts: 3 Apr, 2024

11 Months$ 1,499
Full Stack Developer - MERN Stack

Cohort Starts: 3 Apr, 2024

6 Months$ 1,449

Get Free Certifications with free video courses

  • Introduction to PHP Basics

    Software Development

    Introduction to PHP Basics

    7 hours4.513K learners
  • Website Creation 101: Website Creation using JavaScript

    Software Development

    Website Creation 101: Website Creation using JavaScript

    3 hours4.52.5K learners
prevNext

Learn from Industry Experts with free Masterclasses

  • Certified Ethical Hacking - Demo Class

    Cyber Security

    Certified Ethical Hacking - Demo Class

    19th Jun, Monday8:30 PM IST
  • Expert Webinar: Practical Risk Management Steps for the Threat Hunter

    Cyber Security

    Expert Webinar: Practical Risk Management Steps for the Threat Hunter

    13th Dec, Wednesday11:00 PM IST
  • Expert Webinar: The Five Phases of Ethical Hacking with Kevin King

    Cyber Security

    Expert Webinar: The Five Phases of Ethical Hacking with Kevin King

    30th Nov, Thursday10:00 PM IST
prevNext