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

  • Quote from of.documentation : Π—Π°ΠΌΠ΅Ρ‡Π°Π½ΠΈΠ΅: Π’Π½ΡƒΡ‚Ρ€Π΅Π½Π½ΠΈΠ΅ Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠΈ PHP Π² основном ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΡƒΡŽΡ‚ сообщСния ΠΎΠ± ΠΎΡˆΠΈΠ±ΠΊΠ°Ρ…, ΠΈ Ρ‚ΠΎΠ»ΡŒΠΊΠΎ Π½ΠΎΠ²Ρ‹Π΅ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π½ΠΎ-ΠΎΡ€ΠΈΠ΅Π½Ρ‚ΠΈΡ€ΠΎΠ²Π°Π½Π½Ρ‹Π΅ Ρ€Π°ΡΡˆΠΈΡ€Π΅Π½ΠΈΡ ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΡƒΡŽΡ‚ ΠΈΡΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΡ. Однако, ошибки ΠΌΠΎΠΆΠ½ΠΎ Π»Π΅Π³ΠΊΠΎ ΠΏΡ€Π΅ΠΎΠ±Ρ€Π°Π·ΠΎΠ²Π°Ρ‚ΡŒ Π² ΠΈΡΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΡ с ΠΏΠΎΠΌΠΎΡ‰ΡŒΡŽ класса ErrorException. Π—Π°ΠΌΠ΅Ρ‡Π°Π½ΠΈΠ΅: Π’Π½ΡƒΡ‚Ρ€Π΅Π½Π½ΠΈΠ΅ Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠΈ PHP Π² основном ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΡƒΡŽΡ‚ сообщСния ΠΎΠ± ΠΎΡˆΠΈΠ±ΠΊΠ°Ρ…, ΠΈ Ρ‚ΠΎΠ»ΡŒΠΊΠΎ Π½ΠΎΠ²Ρ‹Π΅ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π½ΠΎ-ΠΎΡ€ΠΈΠ΅Π½Ρ‚ΠΈΡ€ΠΎΠ²Π°Π½Π½Ρ‹Π΅ Ρ€Π°ΡΡˆΠΈΡ€Π΅Π½ΠΈΡ ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΡƒΡŽΡ‚ ΠΈΡΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΡ. Однако, ошибки ΠΌΠΎΠΆΠ½ΠΎ Π»Π΅Π³ΠΊΠΎ ΠΏΡ€Π΅ΠΎΠ±Ρ€Π°Π·ΠΎΠ²Π°Ρ‚ΡŒ Π² ΠΈΡΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΡ с ΠΏΠΎΠΌΠΎΡ‰ΡŒΡŽ класса ErrorException. try-catch deals with exceptions, while if-else are statements for branching program code. - Edward
  • one
    Do not bother with PCP as a whole and even more so with Laravel. The principle of exceptions and the purpose of this mechanism is common to most programming languages. Read about exceptions in general. - teran

1 answer 1

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