php: catch exception and continue execution, is it possible?
Is it possible to catch exception and continue execution of script?
Solution 1:
Yes but it depends what you want to execute:
E.g.
try {
a();
b();
}
catch(Exception $e){
}
c();
c()
will always be executed. But if a()
throws an exception, b()
is not executed.
Only put the stuff in to the try
block that is depended on each other. E.g. b
depends on some result of a
it makes no sense to put b
after the try-catch
block.
Solution 2:
Sure, just catch the exception where you want to continue execution...
try
{
SomeOperation();
}
catch (SomeException $e)
{
// do nothing... php will ignore and continue
}
Of course this has the problem of silently dropping what could be a very important error. SomeOperation() may fail causing other subtle, difficult to figure out problems, but you would never know if you silently drop the exception.
Solution 3:
Sure:
try {
throw new Exception('Something bad');
} catch (Exception $e) {
// Do nothing
}
You might want to go have a read of the PHP documentation on Exceptions.
Solution 4:
php > 7
use the new interface Throwable
try {
// Code that may throw an Exception or Error.
} catch (Throwable $t) {
// Handle exception
}
echo "Script is still running..."; // this script will be executed.
Solution 5:
Yes.
try {
Somecode();
catch (Exception $e) {
// handle or ignore exception here.
}
however note that php also has error codes separate from exceptions, a legacy holdover from before php had oop primitives. Most library builtins still raise error codes, not exceptions. To ignore an error code call the function prefixed with @:
@myfunction();