appson
appson

Reputation: 183

Laravel exception handling without try/catch statement

I'm wondering is a good practice to throw exceptions without try/catch statement. For example

/// Class Driver

class Driver{

 public function setAge($age)
   if(is_string($age)){
      throw new StringException('Age can not be string')
   }
   if($age>100){
      throw new TooLargeNumberException('Age is too large')
   }
}

///Controller

$d= new Driver()
$d->setAge(101) /// return TooLargeNumberException

Or

try{
$d= new Driver()
$d->setAge(101)
}
catch(StringException $e){
 return $e->getMessage()
}
catch(TooLargeNumberException $e){
return $e->getMessage()
}

Please advice me how to handle with exceptions. Which solution is correct? Is it neccesarily to use always try/catch statement?

Upvotes: 1

Views: 3040

Answers (1)

Cyril Graze
Cyril Graze

Reputation: 3890

Laravel has a general exception handler where all uncaught exceptions go to:

App\Exceptions\Handler

There are two methods in this class: report and render with which you can take the necessary actions.

Please see: https://laravel.com/docs/5.8/errors

That is to say, you can throw the exceptions inside class Driver, and not need to handle them specifically in the controller, you can have a general exception handling strategy defined in your Handler class.

Upvotes: 2

Related Questions