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

Trying to understand - from your words we have to always at beginning of function check if parameters exists and right for function then trow error message with info A param not exists B param is wrong etc .. Right ?

1

u/colshrapnel Apr 28 '26 edited Apr 28 '26

Not sure what you mean. When a required parameter doesn't exist, PHP would already tell you that. That's the very purpose of programming errors: to tell the programmer that the code is wrong and also to explain what exactly is wrong.

While from my words, we should only write a code to handle a possible error, if we have a specific handling scenario in mind. In all other cases we should leave the possible error alone, instead of wrapping it into useless (and possibly harmful) try/catch.

1

u/colshrapnel Apr 28 '26

and right for function then trow error message with info A param not exists B param is wrong etc .. Right ?

Speaking of checking if a parameter is "right" - it depends. Sometimes it could be a good thing to do and sometimes it would be superfluous. Like, if you are writing a library that would be used by many people, it's always a good thing to provide helpful error messages, when a parameter is wrong. But in your own application code, usually you don't bother, knowing already that either the data is all right, being validated on entry, or you can deduce the parameter error from the subsequent code error. For example, when your function expects a filename that ends with .jpg, and you give it .png, you will know that from PHP warning that would be thrown.

1

u/arm14789 Apr 28 '26

I only agree here: if function is hard or you are going to write function that used by many other is meaningful to have descriptive errors also mention that function trows error in annotation.
But for simple functions e.g. getFile personally me i would not add error trow, false if Very enough and i'm sure 95% dev do same.