I am writing a console command to update catalog stock, but I am facing some weird issue when trying to load products by sku. I am using this code...

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productRepo = $objectManager->create('Magento\Catalog\Model\ProductRepository');

And then, after getting $sku from a csv read function...

try {
    $product = $productRepo->get($sku);
} catch (Exception $e){
    $product = false;
echo "1"; exit;

I have placed that echo "1"; just to check but that "1" is never reached... result is always [Magento\Framework\Exception\NoSuchEntityException] Requested product doesn't exist

So, how can I catch that Exception?

1 Answer 1


I thought I could catch that using generic php Exception class, but it seems we need to use the concrete throwed Exception

Using this code, then the try/catch block works

try {
    $product = $productRepository->get($sku);
} catch (\Magento\Framework\Exception\NoSuchEntityException $e){
    $product = false;
  • 1
    Actually, you can catch the generic class. But the code above will most likely be inside your namespace, which means that you have to catch \Exception, not Exception. Commented Sep 9, 2019 at 16:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.