Detailed explanation of laravel5 using try catch

  • 2021-08-21 19:57:13
  • OfStack

Using the following code in laravel5 does not catch exceptions


try{
 var_dump($val);
}catch (Exception $e){
 var_dump($e);
echo $e->getMessage();
}

The Laravel 5 controller is forced into the child namespace, so that the Exception class in the root namespace cannot be called directly. The controller of Laravel 4 can be used directly under the namespace. After PHP 5.3, all classes default to the namespace or, if not declared, to the top-level namespace.

So to use the syntax of try catch, either the code starts with use\ Exception or catch (\ Exception $e). So the correct way to use it is


try{
 var_dump($val);
}catch (\Exception $e){
 var_dump($e);<br><br>echo $e->getMessage();
<br>
}

ps: try catch problem in Laravel 5: Exception could not be detected

In a recent project, I tried to use try catch and found that I didn't succeed


try{
 var_dump($val);
}catch (Exception $e){
 var_dump($e) ; 
}

In php, this code should print the value of $e. However, in Laravel 5, it will not. This is because Laravel 5 enforces the use of the PSR standard and the correct namespace must be used.

So to use the syntax of try catch, either the code starts with use\ Exception or catch (\ Exception $e). So the correct way to use it is


try{
 var_dump($val);
}catch (\Exception $e){
 var_dump($e) ; 
}

Summarize


Related articles: