Still not fully understood, why do we need exceptions and try-catch constructs, if there is an if-else? After all, using if else it is also possible to stop the execution of the program in the right place and give an error. Explain the need for exceptions by the example of laravel
1 answer
Well, everything is just an example with if and else.
Suppose there is one query processing point in index.php
$body = runApplication(); if($body['status'] == false ) { echo 'Error: ' . $body['message']; } else { echo $body['body']; } // Π΄Π°Π»Π΅Π΅ Π³Π΄Π΅ ΡΠΎ Π² runApplication Π΅ΡΡΡ Π°Π²ΡΠΎΠ»ΠΎΠ΄ ΠΊΠ»Π°ΡΡΠΎΠ² ΠΊ ΠΏΡΠΈΠΌΠ΅ΡΡ // ΡΠ°ΡΠΌΠΎΡΡΠΈΠΌ ΡΡΠ½ΠΊΡΠΈΡ ΡΠ΅Π½Π΄Π΅ΡΠ° Π³Π»Π°Π²Π½ΠΎΠΉ ΡΡΡΠ°Π½ΠΈΡΡ function render() { if(renderBlock1) { return ['status' => false, 'msg' => 'error']; } if(renderBlock2) { return ['status' => false, 'msg' => 'error 2']; } // ΠΈ Ρ.Π΄. } function renderBlock() { /// ΠΊΠ°ΠΊΠ°Ρ ΡΠΎ Π»ΠΎΠ³ΠΈΠΊΠ° Ρ ΠΎΡΠΈΠ±ΠΊΠΎΠΉ return []; // ΡΠ½ΠΎΠ²Π° ΠΎΠ±ΡΠ°Π±ΠΎΡΠΊΠ° ΠΈ ΠΎΡΠΈΠ±ΠΊΠΈ ΠΈ Ρ.Π΄. } You also need to describe the logic for stopping the application, etc. etc. that's exactly this kind of logic that makes exception a kind of mistake due to which the program cannot continue to work. From the word 'surprise';
Now let's look at an example with Exception.
try { appRun(); } catch (Exception $error) { echo 'Error: ' . $error->getMessage(); } // ΠΈ ΡΠ΅ΠΏΠ΅ΡΡ Π²ΡΠ΅ ΡΡΠΎ Π½Π°Π΄ΠΎ ΡΠ΄Π΅Π»Π°ΡΡ ΡΡΠΎ ΠΏΡΠΎΡΡΠΎ Π²ΡΠΊΠΈΠ½ΡΡΡ exception function rederBlock1 { // ΠΊΠ°ΠΊΠ°Ρ ΡΠΎ Π»ΠΎΠ³ΠΈΠΊΠ° Ρ ΠΎΡΠΈΠ±ΠΊΠΎΠΉ throw new Exception('Error'); } - The fact is that laravel ignores the try blocks in the controller and in case of an error immediately returns its Whoops! Error page! - Artur Han
- Can't ignore, add code with your try cath block - Naumov
|
ΠΠ°ΠΌΠ΅ΡΠ°Π½ΠΈΠ΅: ΠΠ½ΡΡΡΠ΅Π½Π½ΠΈΠ΅ ΡΡΠ½ΠΊΡΠΈΠΈ PHP Π² ΠΎΡΠ½ΠΎΠ²Π½ΠΎΠΌ ΠΈΡΠΏΠΎΠ»ΡΠ·ΡΡΡ ΡΠΎΠΎΠ±ΡΠ΅Π½ΠΈΡ ΠΎΠ± ΠΎΡΠΈΠ±ΠΊΠ°Ρ , ΠΈ ΡΠΎΠ»ΡΠΊΠΎ Π½ΠΎΠ²ΡΠ΅ ΠΎΠ±ΡΠ΅ΠΊΡΠ½ΠΎ-ΠΎΡΠΈΠ΅Π½ΡΠΈΡΠΎΠ²Π°Π½Π½ΡΠ΅ ΡΠ°ΡΡΠΈΡΠ΅Π½ΠΈΡ ΠΈΡΠΏΠΎΠ»ΡΠ·ΡΡΡ ΠΈΡΠΊΠ»ΡΡΠ΅Π½ΠΈΡ. ΠΠ΄Π½Π°ΠΊΠΎ, ΠΎΡΠΈΠ±ΠΊΠΈ ΠΌΠΎΠΆΠ½ΠΎ Π»Π΅Π³ΠΊΠΎ ΠΏΡΠ΅ΠΎΠ±ΡΠ°Π·ΠΎΠ²Π°ΡΡ Π² ΠΈΡΠΊΠ»ΡΡΠ΅Π½ΠΈΡ Ρ ΠΏΠΎΠΌΠΎΡΡΡ ΠΊΠ»Π°ΡΡΠ° ErrorException.ΠΠ°ΠΌΠ΅ΡΠ°Π½ΠΈΠ΅: ΠΠ½ΡΡΡΠ΅Π½Π½ΠΈΠ΅ ΡΡΠ½ΠΊΡΠΈΠΈ PHP Π² ΠΎΡΠ½ΠΎΠ²Π½ΠΎΠΌ ΠΈΡΠΏΠΎΠ»ΡΠ·ΡΡΡ ΡΠΎΠΎΠ±ΡΠ΅Π½ΠΈΡ ΠΎΠ± ΠΎΡΠΈΠ±ΠΊΠ°Ρ , ΠΈ ΡΠΎΠ»ΡΠΊΠΎ Π½ΠΎΠ²ΡΠ΅ ΠΎΠ±ΡΠ΅ΠΊΡΠ½ΠΎ-ΠΎΡΠΈΠ΅Π½ΡΠΈΡΠΎΠ²Π°Π½Π½ΡΠ΅ ΡΠ°ΡΡΠΈΡΠ΅Π½ΠΈΡ ΠΈΡΠΏΠΎΠ»ΡΠ·ΡΡΡ ΠΈΡΠΊΠ»ΡΡΠ΅Π½ΠΈΡ. ΠΠ΄Π½Π°ΠΊΠΎ, ΠΎΡΠΈΠ±ΠΊΠΈ ΠΌΠΎΠΆΠ½ΠΎ Π»Π΅Π³ΠΊΠΎ ΠΏΡΠ΅ΠΎΠ±ΡΠ°Π·ΠΎΠ²Π°ΡΡ Π² ΠΈΡΠΊΠ»ΡΡΠ΅Π½ΠΈΡ Ρ ΠΏΠΎΠΌΠΎΡΡΡ ΠΊΠ»Π°ΡΡΠ° ErrorException.try-catch deals with exceptions, while if-else are statements for branching program code. - Edward