r/PHPhelp • • Apr 27 '26

Runtime vs InvalidArgument exceptions - when to use which?

When should you throw RuntimeException vs InvalidArgumentException in PHP?

I understand that InvalidArgumentException extends LogicException, which is meant for errors detectable before runtime, and RuntimeException is for conditions only discoverable during execution.

But I keep second-guessing myself on cases like this:

function getFile(string $path): string
{
    if (!file_exists($path)) {
        throw new ???Exception('File not found.');
    }
    return file_get_contents($path);
}

The argument $path is technically valid -- a non-empty string, correct type. But the file it refers to does not exist. Is that a RuntimeException because the absence is only discoverable at runtime? Or is it an InvalidArgumentException because the argument I passed did not correspond to anything real?

Where do you draw the line, and how do you think about this distinction?

10 Upvotes

33 comments sorted by

View all comments

Show parent comment

1

u/arm14789 Apr 28 '26

echo is example man, only dumb dump on white page Error: file not found or unreadable , e.g. if user provided wrong file he has to be aware right now and retry uplaod

1

u/colshrapnel Apr 28 '26

only dumps dump on white page

Yes, and like I said, It shouldn't be doing that. Instead, it must be

$content = getFile('data.txt');
echo $content;

In case the file is all right, it will show the contents. In case of error, PHP will inform the Reddit programmer, and also show you the "You broke Reddit" page. What else could you possibly want?

1

u/colshrapnel Apr 28 '26

man,

if user provided wrong file

is absolutely different matter

and nowhere is a golden middle case. If it's a user-provided file, you are doing exactly that: checking if a file was provided, before even trying to read it.

Hence my other example:

if (file_exists($path)) {
    $content = getFile('data.txt');
    echo $content;
} else {
    echo "File not found";
}

But it's nowhere a golden middle, because it's a very specific case, when, in fact, if there is no file, we aren't even trying to read it at all.