pain.reign
pain.reign

Reputation: 371

How to force catching exceptions PHP

How to force catching exceptions in PHP?

I want to force exception catching if method may return and exception and is not added to try catch block.

For example:

If an exception is not thrown developer may never know that certain kind of exception may be thrown by the method he uses. So he won't catch it. I want to make sure that every exception that can be thrown will be caught.

In case it is not, I want a fatal error, or at least an exception.

Upvotes: 1

Views: 6477

Answers (2)

pain.reign
pain.reign

Reputation: 371

I decided to share what I do for myself considering this question.

I will add compilation mechanism to my application. So it won't be working if its not compiled first.

This will help me to force coding practices on developers and won't slow an application.

======================

Sorry, I cannot find a way to make it without slowing application. The best thing for the moment that comes to my mind is to check file modification time when it gets included. If its not equal to compilation time then throw an exception about compilation.

But it checks date and time of all files that participated in script run after all. So if you run 1000 files in your script execution, on my pc it gets slowed for 0.022 sec. If there are around 50 files included in your script run then it is slowed by 0.0015 sec

In most cases running this kind of application will still be cheaper then fixing bugs made by developers. But it depends how fast you want your application to be.

Upvotes: 0

hek2mgl
hek2mgl

Reputation: 158250

Update: In comments it points out, that the former answer was not the actual answer to the problem. The detection of uncaught exceptions, or potentially uncaught exceptions in PHP is not supportet by the PHP parser itself. (Not like the Java compiler). You'll have to use external tools for statical code analysis to improve the quality of your code. I found this interesting answer for example: https://stackoverflow.com/a/8268875/171318


Original Answer:

You can register a function as global exception handler using set_exception_handler(). This function will be called by the PHP engine if an exception was not caught.

Example (from PHP manual):

<?php
function exception_handler($exception) {
  echo "Uncaught exception: " , $exception->getMessage(), "\n";
  exit(1);
}

set_exception_handler('exception_handler');

throw new Exception('Uncaught Exception');
echo "Not Executed\n";
?>

Upvotes: 3

Related Questions