In PHP 7.1+, you can catch multiple exceptions in the following way:
// PHP 7.1+
try {
// ...
} catch (RuntimeException | InvalidArgumentException $e) {
// ...
} catch (BadMethodCallException $e) {
// ...
}
In the code above you can see that in the both, RuntimeException and InvalidArgumentException, have a common catch block and BadMethodCallException has a different catch block.
In versions prior to PHP 7.1, you can catch multiple exceptions in the following ways:
- By Creating Common Error Handlers;
- By Grouping Exceptions;
- By Using
instanceof; - By Using
get_class().
Creating Common Error Handlers
You could define functions/methods that handle common error code and call them on individually caught exceptions, for example, like so:
try {
// ...
} catch (RuntimeException $e) {
handler1();
} catch (InvalidArgumentException $e) {
handler1();
} catch (BadMethodCallException $e) {
// ...
}
Grouping Exceptions
You could group common exception classes and catch them collectively, for example, like so:
class HttpException extends RuntimeException {}
class RequestException extends HttpException {}
class ResponseException extends HttpException {}
try {
// ...
} catch (HttpException $e) {
// ...
} catch (BadMethodCallException $e) {
// ...
}
Or, using an interface:
interface HttpExceptionInterface {}
class RequestException extends RuntimeException implements HttpExceptionInterface {}
class ResponseException extends RuntimeException implements HttpExceptionInterface {}
try {
// ...
} catch (HttpExceptionInterface $e) {
// ...
} catch (BadMethodCallException $e) {
// ...
}
Using instanceof
You could catch all exceptions with "Exception" and then check which exception was thrown with instanceof, for example, like so:
try {
// ...
} catch (Exception $e) {
if ($e instanceof RuntimeException || $e instanceof InvalidArgumentException) {
// ...
return;
} elseif ($e instanceof BadMethodCallException) {
// ...
return;
}
throw $e;
}
Using get_class()
You could catch all exceptions with "Exception" and then check which exception was thrown with get_class, for example, like so:
try {
// ...
} catch (Exception $e) {
switch (get_class($e)) {
case RuntimeException::class:
case InvalidArgumentException::class:
// ...
break;
case BadMethodCallException::class:
// ...
break;
default:
throw $e;
}
}
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.