Why do we use a try block to throw exceptions. we cannot just throw and catch them without a try block. What is its importance?

I am trying to figure out the need for a try block to handle exceptions.

I am studying custom error handling in php and the code is as follows:

class customException extends Exception{ public function errorMessage(){ return "Error at line ".$this->getLine()." in ".$this->getFile()."<br>".$this->getMessage()." is not a valid email address"; } } $email=" someone@example.com "; try{ if(!filter_var($email,FILTER_VALIDATE_EMAIL)){ throw new customException($email); } } catch(customException $e){ echo $e->errorMessage(); } 
+5
source share
4 answers

Code executed in a try block can throw various types of exceptions

 try { thingThatMightBreak(); } catch (CustomException $e) { echo "Caught CustomException ('{$e->getMessage()}')\n{$e}\n"; } catch (Exception $e) { echo "Caught Exception ('{$e->getMessage()}')\n{$e}\n"; } 
+3
source

If you select an exception without a try / catch block, a fatal error will occur. An error message appears indicating the reason for this avoidable circumstance: "Fatal error: unclean exception", and your program terminates without executing the remaining code; see here . Manual mentions that this is a common result:

if the handler was not defined using set_exception_handler ()

Setting the exception handler allows you to avoid the "Fatal error" message and allows you to handle the exception as you wish, but after the handler stops the program; see here .

The try / catch block provides code a opportunity to try to execute. If an exception occurs, you can safely handle it by catching it, which will prevent the program from abruptly stopping as follows:

 <?php try { $myvar = null; if (!isset($myvar)) { throw new Exception("unset variable"); } } catch (Exception $e) { echo $e->getMessage(); } echo "\nStill carrying on and on ...\n"; 

Watch the demo

+2
source

Unused exceptions will terminate the program.

By the way, it can also throw exceptions and handle them from the try / catch block. Here is the php funtion documentation page set_exception_handler ()

+2
source

try / catch is designed to handle exceptions and recover from them. If you throw away without a catch, your program will stop running. If an exception occurs and you catch it, you can do something with it, for example, repeat it the way you do now.

+1
source

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


All Articles