Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

RuntimeException

An exception for errors that only show up at run time.

Syntax

throw new RuntimeException(string $message = "", int $code = 0, ?Throwable $previous = null)

Parameters

ParameterTypeDescription
$messagestringOptional. The error text.
$codeintOptional. The error code.
$previous?ThrowableOptional. The original exception.

Return value

RuntimeExceptionThe exception object.

Examples

A settings file is missing:

<?php
 
function loadConfig(string $file): array
{
    if (!is_file($file)) {
        throw new RuntimeException("Config not found: $file");
    }
 
    return parse_ini_file($file);
}
 
try {
    loadConfig('missing.ini');
} catch (RuntimeException $e) {
    echo $e->getMessage();
}

Output:

Config not found: missing.ini

Notes

Throw InvalidArgumentException when a function was called wrongly; RuntimeException when the call is right but something went wrong: a missing file, an unavailable service.

See also

In the tutorial

  • Exceptions — Exceptions in PHP — throw, try, catch and finally, custom exception classes and built-in errors.

Thanks for reading!

Donate to the site — we work hard for you.