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
}
powtac
  • 40,542
  • 28
  • 115
  • 170
Cheluis
  • 1,402
  • 3
  • 22
  • 51

4 Answers4

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";
}
Cyrille
  • 3,427
  • 1
  • 30
  • 32
powtac
  • 40,542
  • 28
  • 115
  • 170
  • There could be a automatic Error to Exception transformer: http://stackoverflow.com/a/10919969/22470 – powtac Jun 06 '12 at 18:28
4

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

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

Rawkode
  • 21,990
  • 5
  • 38
  • 45
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.

Susam Pal
  • 32,765
  • 12
  • 81
  • 103
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.

Community
  • 1
  • 1
Andrey Rudenko
  • 1,271
  • 20
  • 34