Why isn't my Exception being caught by catch?

前端 未结 4 558
梦毁少年i
梦毁少年i 2020-12-18 18:55

I have some code that looks like this

# Try to import file
try
{
    DataManager::fileImport($_FILES[\'datafile\'][\'tmp_name\'], 
                                   


        
相关标签:
4条回答
  • 2020-12-18 19:21

    Solution

    I neglected to specify use \Exception; in the file containing the try/catch.

    Pondering

    I know it's intentional that each namespace in PHP should define its own Exception for many reasons, but I still find it odd that catch(Exception e) didn't cause any errors when Exception in that context wasn't defined. If I were to write new Exception() I would get an error.

    Oh well, at least I learned something.

    0 讨论(0)
  • 2020-12-18 19:28

    You might have an issue with your DataManager class because i copied your code, adapted it to run and i get the exception handled... You problem is elsewhere...

    class DataManager {
        static function fileImport($filepath, $zones, $statuses){
            throw new Exception('SOME EXCEPTION');
        }
    }
    
    try{
        DataManager::fileImport('', '', '');
    }catch(Exception $e){
        print 'Herp.';
    }
    

    Results in

    Herp.
    
    0 讨论(0)
  • 2020-12-18 19:38

    Strange. If i run this code i get the "Herp."

    <?php
    
    class DataManagerTest {
        static function fileImport($filepath, $zones, $statuses)
        {
            throw new Exception('SOME EXCEPTION');
        }
    }
    
    # Try to import file
    try
    {
        DataManagerTest::fileImport("param1","param2","param3");
    }
    catch(Exception $e)
    {
        print 'Herp.';
    }
    
    
    ?>
    
    0 讨论(0)
  • 2020-12-18 19:43

    4 years later...

    @Hubro, thank you for saving me with that namespace fix!

    It does seem counterintuitive at first that it's necessary when throwing a root-level Exception, even though it ultimately makes sense in the general context of namespaces.

    For anyone who doesn't want to utilize @Hubro's file-level fix:

    use \Exception;

    You could instead add the backslash in front of Exception in the higher level catch block:

    } catch (\Exception $e) {

    We could all benefit from someone smarter than me providing suggestions on best practices around defining a custom Exception for each namespace. Any takers?

    0 讨论(0)
提交回复
热议问题