33

I understand what try-catch statements do, but from reading the documentation on php.net, I would not be able to implement one into my own code. I need a real example to help me understand.

How can I turn this example into a try-catch statement, if the upload was not successful?

$move = move_uploaded_file($_FILES['file']['tmp_name'], $_SERVER['DOCUMENT_ROOT'].'/uploads/'.$_FILES['file']['name']);

if (!$move) {
    die ('File didn\'t upload');
} else {            
    //opens the uploaded file for extraction
    echo 'Upload Complete!';
}

This may not be a good example to work with, but any help would be appreciated.

1

4 Answers 4

52

You could do it like this.

try {
    //throw exception if can't move the file
    if (!move_uploaded_file( ... )) {
        throw new Exception('Could not move file');
    }

    //do some more things with the file which may also throw an exception
    //...

    //ok if got here
    echo "Upload Complete!";
} catch (Exception $e) {
    die ('File did not upload: ' . $e->getMessage());
}

It is a bit pointless for the above example, but you should get the idea. Note that you can throw the exception(s) from anywhere (e.g. within a function/method that you call from withing the try{}) and they will propagate upwards.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your reply and answer! I understand this wasn't a great example. When would it be suitable to use an Exception? thanks!
I don't thin there are good or bad examples. Try/Catch statements are useful, when they are useful. The only thing you should matter, is php will throw E_ERROR or E_WARNING when a function is misused.
9

Well, if you want to use exceptions, you could do something like:

function handleUpload() {


    $move = move_uploaded_file($_FILES['file']['tmp_name'], $_SERVER['DOCUMENT_ROOT']."/uploads/".$_FILES['file']['name']);

    if (!$move) {
       throw new Exception('File Didnt Upload');
    }

}

try {
   handleUpload();
   echo "File Uploaded Successfully";
} catch(Exception $ex) {
   die($ex->getMessage);
}

I know this may seem like bloat - but you can call the method from anywhere in the call stack, and catch the exception at any point.

1 Comment

Just a note, that exception handling is a lot more useful if you have a class hierarchy for your exceptions. It's generally useful to use catch with specific Exception sub-classes, and this way you can choose what problems are handled at what level of the code.
7

try-catch statements are used to handle exceptions. I don't believe that the function move_uploaded_files can throw and exception, as such I think that you code is written is correct. After the call, you look at the return code. If it's false, you end processing, otherwise you are report success.

2 Comments

His example is correct but I think the point was that he's trying to learn about exceptions rather than trying to fix/improve the sample code.
Thanks Everyone for your quick responses! This seems to not be the best example to learn from. When would be a good/right time to use an Exception then?
4

According to a similar post in PHPbug, only OO code (Object-Oriented code) throws exceptions. That would mean that functions such as move_uploaded_file won't throw their own exceptions, but some other code will.

1 Comment

This is important that "only OO code (Object-Oriented code) throws exceptions." if you want to use it in directly a php functions (out of any class) you won't get throw message...

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.