Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Try-Catching Exceptions and PHP Errors

Premium
3 min read

Exceptions are the mechanism to catch some invalid behavior and gracefully handle them instead of just showing "500 server error" to the users.

Take a look at this example:

public function __invoke()
{
$data = [['name' => 'John Doe', 'email' => '[email protected]', 'date' => '23-04']];
 
try {
$this->import($data);
} catch (ImportHasMalformedData $e) {
return redirect()->route('dashboard')->with('message', 'Uh oh, the import has failed. Try again later or contact support');
}
 
return 'Imported';
}

This snippet means that in case of ANY Exception, the user would get redirected back and see the error message.

But what if we're expecting something specific to happen?


Catching a Specific Laravel Exception

Try-catch is way more helpful when catching a specific Exception. Laravel and 3rd party packages often offer...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

F
Freezy ✓ Link copied!

In the first example provided, you use the method import ($data) $this->import($data), however, in your last try catch statement, you use ImportController::importData(). Is there a connection between the 2 import methods? Does this mean that the ImportController has a static method called importData() and a regular method called import($data)? Are they the same thing (does laravel 'know' a method + a parameter can be directly called as methodParameter())? Or is this a typo?

N
Nerijus ✓ Link copied!

No, it's a basic method in this case, not static. This part is taken from the Handling Exceptions and Errors in Laravel so better refer there for more about exceptions.

F
Freezy ✓ Link copied!

Thank you very much!

DS
Dmytro Sakharuk ✓ Link copied!

It would be appropriate to provide information about the "finally" block.

Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes. https://www.php.net/manual/en/language.exceptions.php#language.exceptions.finally

M
Modestas ✓ Link copied!

This course/lesson was more focused on the PHP errors and not on overall error handling. We have a separate tutorial about the exceptions, where we talk about finally there :)