should I use an exception here?

Go To StackoverFlow.com

4

I'm new to exceptions and am trying to figure out when is appropriate to use them. In the following php code I would like to change echo (no need to tell the user) to simply log the message. Should I just replace echo with log->notice(...) (for example) or should I be using an exception (which I plan to log anyway).

if (file_exists($file)) {
    echo 'File already exists and will be overwritten.';
}

Also, If I should be using an exception, then how would I use one properly in this scenario?

2012-04-04 16:49
by Isius


1

Exceptions are designed generally to handle unexpected behavouir - such as an error or problem.

In the case of your example above, I'd argue it wasn't needed, as you may expect the file to exist and should really write your program in a way to flow if there is a file there already (Like you have done). It all depends on what you expect to happen, and not.

A Case of normal use might be:

try
{
    some_function();
}
catch (Exception $e)
{
    echo 'Function didn\'t behave as expected, please try again, here is the error: '.$e->getMessage();
}
2012-04-04 16:56
by BenOfTheNorth


1

Exceptions are standard ways of handling errors .. but they may be some instances where you need to use exception.

If you just want to validate a file .. no need of exception .. if false output would need you to redirect or has a chain reaction or may you are developing a framework etc ... i would advice you use Exception

try
{
    if (file_exists($file)) {
           throw new Exception('File already exists and will be overwritten.');
    }
}
catch (Exception $e)
{
   header("Location: error?msg=". base64_encode($e->getMessage()));
}

Conclusion

What you are using the script for would determine if its better for you to use exception or not

I hop this helps

Thanks

:)

2012-04-04 17:06
by Baba


1

Exceptions are meant to break the flow of execution if an error is encountered. It all depends on how you construct the flow, if you want to stop the flow because a file exists you can do the following:

try {
    if (file_exists($file)) {
        throw new Exception(sprintf('File already exists and will be overwritten';
    }

    // If above conditional is realized, no code from this point forward will be
    //  executed

} catch (Exception $e) {
    error_log($e->getMessage());
}

In your specific example, I think it's ok to keep the code as is, because it appears to only be a warning, meaning that you do not want to break the flow of execution, but rather continue with code execution after the warning.

If you really wanted to use exceptions, you could implement nested exceptions, but it gets complicated and ends up being overkill.

More info on exceptions via PHP docs.

Should I just replace echo with log->notice(...)

I would, unless you want the user to be aware of the issue.

2012-04-04 17:06
by Mike Purcell
Ads