Home > Backend Development > PHP Tutorial > How to use try catch in laravel5?

How to use try catch in laravel5?

php中世界最好的语言
Release: 2023-03-18 06:58:01
Original
2924 people have browsed it

We know that try catch is a very important attribute in laravel5, so today we will bring you the relevant knowledge about using try catch in laravel5, let’s take a look together

Using the following code in laravel5 does not catch the exception

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


## Laravel 5 era

Controller is forced to be placed in the childnamespace , so that the Exception class under the root namespace cannot be called directly. Laravel 4 controllers can be used directly under the namespace. After PHP 5.3, all classes will be in the namespace by default. If not declared, they will be in the top-level namespace by default.

So to use try catch syntax, either use use \Exception at the beginning of the code, or use 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>
}
Copy after login


ps: try catch problem in Laravel 5: Exception cannot be detected

In a recent project, I tried to use try catch and found that it has not been successful

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


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

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

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

I believe you have mastered the methods after reading these cases. For more exciting information, please pay attention to other related articles on the php Chinese website!

Related reading:

php uses git deployment environment

Some use cases of Git

Detailed explanation of javascript data types and git usage code

The above is the detailed content of How to use try catch in laravel5?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template