Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP rename() doesn't throws exception on error

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
}
like image 479
Cheluis Avatar asked May 15 '12 19:05

Cheluis


People also ask

How can we rename a file in PHP?

PHP rename() Function rename("images","pictures"); rename("/test/file1. txt","/home/docs/my_file. txt");

How can I get error code from exception in PHP?

The getMessage() method returns a description of the error or behaviour that caused the exception to be thrown.

What is rename function in PHP?

rename() function in PHP The rename() function renames a file or directory. The function returns TRUE on success or FALSE on failure.

Does throwing an exception return PHP?

When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an " Uncaught Exception ... " message, unless a handler has been defined with set_exception_handler().


1 Answers

"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
}
like image 113
powtac Avatar answered Oct 27 '22 13:10

powtac