📜 ⬆️ ⬇️

try ... catch VS if ... else. What, when and why?

This article is designed for two types of developers:
- who is not familiar with exceptions
- who tries to find more reasonable use of exceptions

In the article I will talk about the very basics of exceptions, about how you can do without them, as well as about how I see the correct use of certain features of the language ...

The evolution of programming languages ​​sometimes leads to dramatic changes in the developers' worldview. In the world of PHP, this happened when the fifth branch appeared, which brought a new object model, new sets of built-in functions and new error handling methods ...
')
Those who started to get acquainted with PHP (hereinafter I will imply the fifth version), after another procedural programming language, did not understand what was happening in the transition from 4k to 5k and continued to draw code with familiar functions that are on the same level relation to each other, as well as each action is checked for a successful return code. But those who knew about exceptions and classes ...


Theory


Exception - a signal sent by the program to the interpreter, about the occurrence of an abnormal (exceptional) situation during the execution of a code.

In PHP, working with exceptions is based on the same principles as everywhere else. To generate an exception, use the throw operator, to which an exception object is passed, which takes two optional parameters in the constructor: an exception message and an exception code.

throw new Exception(\\\"This is exception message\\\", $exception_code);


To catch an exception, use the try ... catch construction. In the try block, operations are performed that can lead to an exception, and the catch block allows you to decide what to do if an exception has been thrown.
try {
throw new Exception(\\\"Exception message\\\");
echo \\\"That code will never been executed\\\";
} catch (Exception $e) {
echo $e->getMessage(); // \\\"Exception message\\\"
}


As you can see from the example, when an exception is thrown, the rest of the code in the try block will not be executed, and control will be passed to the catch statement, in which we specify what the object to which the thrown exception will be passed will be called (in our case, $ e) . Inside the block of the catch operator, based on the data from the exception, we can apply some action depending on the situation. Now we just brought out the message that was transmitted by the exception.

The Exception object (which, by the way, can be inherited) has the following set of final (final) methods:
final function getMessage(); //
final function getCode(); //
final function getFile(); //
final function getLine(); //
final function getTrace(); //
final function getTraceAsString(); //


Practice


When is it convenient to use exceptions? Yes, always, when a function or method can come to an error situation! Using the built-in functions mysql_connect () and mysql_select_db () as an example, if they threw exceptions during a connection error and database selection, respectively, the code would look like this:
try {
mysql_connect($hostname, $username, $password);
mysql_select_db($dbname);
} catch (Exception $e) {
echo $e->getMessage(); // ,
}


And depending on the result, we would:

* would successfully join the DBMS and select the database (the code in the catch block would not be executed)
* if the connection with the DBMS failed, they would output the corresponding error and rolled up the session
* in case of a database selection error, the user would be informed about this trouble.

Now it's time to ask: \\\ "And why do we need such a complicated thing, if you can use the if operator? \\\".

The first answer is: \\\ "Because the code is more readable, and error handling is displayed in a separate \\\ block." If we used the if statement, the code would look like this:
$connId = mysql_connect($hostname, $username, $password);
if (false == $connId) {
echo \\\" \\\";
}

$flag = mysql_select_db($dbname);
if (false == $flag) {
echo \\\" .\\\";
}


Agree that in the previous version the code looks more understandable. But that is not all. Now it’s not necessary to deal with these errors directly to the developer - it’s enough to throw an exception, but you can handle it at a higher level. You can also pass exceptions with a chain (chain) to the top:
class MyException extends Exception {}

try {
try {
//...
throw new Exception(\\\"inner\\\");
//...
} catch (Exception $e) {
throw new MyException(\\\"outer\\\");
}
} catch (MyException $e) {
echo $e->getMessage(); // \\\"outer\\\"
}


Performance


Trying to reach the truth, he conducted several experiments with various types of functions.
The first type returned the status true and was checked by the operators if ... else
The second type returned the status false and was checked by the if ... else statements
The third type simply performed the actions and returned nothing. Tested with try ... catch
The fourth type always threw an exception and checked it in a try ... catch

Results:
True: 0.72382092475891
False: 0.85190796852112
No exception: 0.72565317153931
Exception: 14.176206827164


As expected - throwing exceptions is a rather expensive operation, but both options for successful execution passed level tests.
Tests were conducted on primitive addition functions, but in 1cc iterations

findings


When to use exceptions? Always, when an error or non-standard behavior of the program is implied, as well as when the decision to process the result has to be shifted to a higher level.
And what to do with the if operator and boolean statuses of working off functions? Leave them. But only where they are really needed. Ie where the logical operator implies the use of the result in calculations rather than controlling the flow of execution. Ie all successful completion of functions no longer need to notify operator return true, if this logical value is not useful for further calculations. And at the same time, all statuses of completion of functions with errors can be changed from the return false format to the throw format new Exception ()
What you need to remember? The use of exceptions assumes that all code is executed with the status true (without errors), but if an error occurs, then there is always room for processing it in the catch block.

Source: https://habr.com/ru/post/21376/


All Articles