Try, Catch; Finally in PHP: The error and exceptions handling is critical in developing any type of application. Understanding the origin point of an error so that appropriate action is taken ensures more quality to the application. It also facilitates the identification of more technical mistakes as problems when connecting to the database or error in a particular class, for example. Legacy systems that possess a try, catch, and finally structure that, implemented efficiently, enable faster maintenance and, therefore, the lifetime of the system increases considerably.
Try, Catch and Finally make up a large structure that is part of the error handling in applications developed in PHP. It enables the treatment of practically exceptions and can then be used in all application screens. The simplicity of the structure is a differential, and will be explained following:
try {
} catch (Exception $e){
} finally{
}
The first block structure (try) will allocate all the code that needs to be validated. If an error is found, the cursor is automatically redirected to the second part of the structure (catch). In the error handling block, the variable “$ e” stores the error message, identified by the system. From there, the whole treatment of error is the developer’s discretion.
Finally, the last block of the frame (finally) will be triggered regardless of the result of the validation of the code. Usually, the statement implemented in this block is used to “clean” variables or other resources that consume memory on the server.
The structure can still rely on different treatments for each type of exception thrown. That’s because PHP provides several bug formats, adapting each to a respective class:
try {
} catch (InvalidArgumentException $e){
} catch (RangeException $e){
} catch (Exception $e){
} finally{
}
In the example you can see how is the dealings of specific errors. Each error handling class can then trigger a different type of code according to the error returned by the language. Thus, it is possible to treat more effectively the possible errors that can be displayed in the execution of the source code that will be implemented and validated by the structure.
Visit our blog and check out more content!
Know Scriptcase?
You might also like…