8

I'm working with a php application, and there is a line that moves a file. I enclosed the method within a try...catch block so, if a error is thrown, can manage a rollback system. But the exception is never catched, so, renames throws any kind of exception? Do I need to try with another method?

Thanks

Code above:

try{ if(rename($archivo_salida, $ruta_archivos)){ //anything; } }catch (Exception $e) //do something } 

4 Answers 4

10

"Normal" PHP functions don't throw exceptions.

Change your code to simulate an exception:

try { if (rename($archivo_salida, $ruta_archivos)) { //anything; } else { throw new Exception('Can not rename file'.$archivo_salida); } } catch (Exception $e) { //do something, such as echo 'Caught exception: ', $e->getMessage(), "\n"; } 
Sign up to request clarification or add additional context in comments.

1 Comment

There could be a automatic Error to Exception transformer: stackoverflow.com/a/10919969/22470
4

rename() only ever returns true/false - there is no thrown exception.

http://php.net/manual/en/function.rename.php

Comments

3

It returns FALSE on failure. See http://php.net/manual/en/function.rename.php

If you really need an exception to be thrown when the rename fails, you can do this:

if (rename($archivo_salida, $ruta_archivos)) { // anything; } else { throw new Exception("Rename failed."); } 

Now, you can wrap this around a try {} catch {} block where ever you are invoking this code.

Comments

1

You can also use the same approach as described in this answer: https://stackoverflow.com/a/43364340/563049

Create a custom exception class and use it's static constructor method with or operator after rename().

Exception class:

class CustomException extends Exception { static public function doThrow($message = "", $code = 0, Exception $previous = null) { throw new Exception($message, $code, $previous); } } 

Usage:

try { rename($archivo_salida, $ruta_archivos) or CustomException::doThrow('Renaming failed.'); } catch (Exception $e){ //do something } 

Note

If you are using PHP 7 and higher - you can rename static method doThrow() to simply throw(), since in PHP 7 and higher it's allowed to use reserved keywords as method names.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.