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. 

Post Graduate Program: Full Stack Web Development

in Collaboration with Caltech CTMEEnroll Now
Post Graduate Program: Full Stack Web Development

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.

New Course: Full Stack Development for Beginners

Learn Git Command, Angular, NodeJS, Maven & MoreEnroll Now
New Course: Full Stack Development for Beginners

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.

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

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

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.
  • *According to Simplilearn survey conducted and subject to terms & conditions with Ernst & Young LLP (EY) as Process Advisors