简体   繁体   中英

php how to catch exception when assigning to variable

I have some classes in my code. From these classes I initiate objects, say

$c = new category ($myGoodObject->categoryId); 

This should give the category object of myGoodObject. However, for example if a categoryId of say 1000 is not defined in database, the class throws an exception.

How to I catch this? And what is the best practice for initiating/loading objects from database that sometimes may not exist? How to avoid failure?

Thanks!

EDIT:

I tried this:

try {
$c = new category (1000);
} catch (Exception $e) {return false;}

but it didn't work.

try
{
    $c = new category ($myGoodObject->categoryId); 
} 
catch (Exception $e) 
{
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

As for best practice, you should first attempt to read the database to see if the value exists, if not, you don't attempt to create the object, therefore avoiding the need for exceptions.

If it throws an exception use a try..catch block

try {
   //try assigning 
catch (Exception $e) {
   //do something
}

Look here for more details on exceptions

don't catch it, just make sure it is there before using it...

if(isset($myGoodObject->categoryId)){
    $c = new category ($myGoodObject->categoryId); 
    //...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM