try {
$attempts = 0;
retry:
throw new Exception('Oops!');
} catch (Exception $e) {
if ($attempts < 4) {
$attempts++;
echo 'Fail - trying again...'.PHP_EOL;
sleep(1);
goto retry;
}
echo $e->getMessage().PHP_EOL;
}
The retry keyword can be used in a catch
block to optionally execute an abritraty statement before jumping to the top of the try
block.
# Litteral number example
try {
throw new Exception('Oops!');
} catch (Exception $e) {
retry 4 {
echo 'Fail - trying again...'.PHP_EOL;
sleep(1);
}
echo $e->getMessage().PHP_EOL;
}
# Constant examples
const RETRY_TIMES = 4;
try {
throw new Exception('Oops!');
} catch (Exception $e) {
retry RETRY_TIMES { sleep(1); }
echo $e->getMessage().PHP_EOL;
}
try {
throw new Exception('Oops!');
} catch (Exception $e) {
retry \Foo\RETRY_TIMES { sleep(1); }
echo $e->getMessage().PHP_EOL;
}
try {
throw new Exception('Oops!');
} catch (Exception $e) {
retry \Foo\Bar::RETRY_TIMES { sleep(1); }
echo $e->getMessage().PHP_EOL;
}
# Litteral number example
try {
throw new Exception('Oops!');
} catch (Exception $e) {
retry 4;
echo $e->getMessage().PHP_EOL;
}
# Constant examples
const RETRY_TIMES = 4;
try {
throw new Exception('Oops!');
} catch (Exception $e) {
retry RETRY_TIMES;
echo $e->getMessage().PHP_EOL;
}
try {
throw new Exception('Oops!');
} catch (Exception $e) {
retry \Foo\RETRY_TIMES;
echo $e->getMessage().PHP_EOL;
}
try {
throw new Exception('Oops!');
} catch (Exception $e) {
retry \Foo\Bar::RETRY_TIMES;
echo $e->getMessage().PHP_EOL;
}
Possibly useful in async contexts?
try {
throw new Exception('Oops!');
} catch (Exception $e) {
retry {
echo 'Fail - trying again...'.PHP_EOL;
sleep(1);
}
}
try {
throw new Exception('Oops!');
} catch (Exception $e) {
retry INF {
echo 'Fail - trying again...'.PHP_EOL;
sleep(1);
}
}
try {
throw new Exception('Oops!');
} catch (Exception $e) {
retry;
}
Removed: It is impossible to disambiguate a expr
and statement
at the parser level, so the following syntax examples are not possible. The statements must always be wrapped with {}
.
try {
throw new Exception('Oops!');
} catch (Exception $e) {
retry 4 sleep(1);
echo $e->getMessage().PHP_EOL;
}
try {
throw new Exception('Oops!');
} catch (Exception $e) {
retry sleep(1);
}
I like the following syntax:
And also (possibly easier to implement and prevent b/c issues?)
Having a specific
retry
keyword may impose breaking code issues for projects, so I still think I prefer my first solution which should be possible to implement without breaking b/c (I think!)