Exception Handling without using 'Catch' keyword - php

I want to create a class in my framework for exception handling.
How can write the class to be able doing exception handling without using try catch in my codes?
Here is a example:
I tried but couldn't write the code here
exception.php
class Soroush_Exception extends
//some code here
}
===============================
file1.php
$a = 2;
if ($a != 3)
{
throw new Soroush_Exception("Error");
}
//and here I want to show it without using catch with a static method
echo Soroush_Exception::show();
sorry for bad english

Use trigger_error function: php.net/trigger_error

Set a class' method as exception handler - it will catch any exception, that was not catched explicitly with a catch statement.
The problem is that exception stops execution of the script to the point where it is catched, and continue from the catch afterwards. If there is no catch, you still can execute code in the exception handler, but after the handler method the script will stop.

Related

Handle specific Exceptions in php

I want to catch a specific Exception and handle it properly. However, I have not done this before and I want to do it in the best way.
Will it be correct to create a separate class something like
class HandleException extends Exception
{
//my code to handle exceptions;
}
and in it have different methods handling the different exception cases? As far as I understand, the Exception class is like an "integrated" class in php so it can be extended and if an Exception is caught it is not obligatory to terminate the flow of the program?
And, an instance of this class will be created when an exception is caught? Sth. like
catch ( \Exception $e ) {
$error = new HandleException;
}
You CAN extend the basic Exception object with your own, to provide your own exception types, e.g.
class FooExcept extends Exception { .... }
class BarExcept extends Exception { .... }
try {
if ($something) {
throw new FooExcept('Foo happened');
} else if ($somethingelse) {
throw new BarExcept('Bar happened');
}
} catch (FooExcept $e) {
.. foo happened, fix it...
} catch (BarExcept $e) {
... bar happened, fix it ...
}
If an Exception is caught, then the program DOESN'T necessarily have to abort. That'd be up to the exception handler itself. But if an exception bubbles always back up to the top of the call stack and ISN'T caught, then the entire script will abort with an unhandled exception error.
From the manual
Multiple catch blocks can be used to catch different classes of
exceptions. Normal execution (when no exception is thrown within the
try block) will continue after that last catch block defined in
sequence. Exceptions can be thrown (or re-thrown) within a catch
block.
So you can do something like this:
try {
// some code
} catch ( HandleException $e ) {
// handle sthis error
} catch ( \Exception $e ) {
// handle that error
}
This will handle different exceptions. You can also use the finally keyword with newer versions of PHP.

PHP - Can't catch exception thrown by Google API lib

I want to catch an exception that is thrown by the Google API PHP library, but for some reason it generates a 'Fatal error: uncaught exception' before reaching my catch block.
In my app I have something like this:
try {
$google_client->authenticate($auth_code);
} catch (Exception $e) {
// do something
}
This is Google_Client's authenticate():
public function authenticate($code)
{
$this->authenticated = true;
return $this->getAuth()->authenticate($code);
}
The authenticate($code) above is Google_Auth_OAuth2::authenticate(), which at some point throws the exception:
throw new Google_Auth_Exception(
sprintf(
"Error fetching OAuth2 access token, message: '%s'",
$decodedResponse
),
$response->getResponseHttpCode()
);
If I put a try/catch block in the Google_Client's authenticate, it catches the exception, but without it the program just dies instead of reaching the main try/catch block from my app.
As far as I know this shouldn't be happening. Any ideas?
The problem was that the try/catch block was in a namespaced file and PHP requires you to use "\Exception". More info: PHP 5.3 namespace/exception gotcha
Example (taken from the link above):
<?php
namespace test;
class Foo {
public function test() {
try {
something_that_might_break();
} catch (\Exception $e) { // <<<<<<<<<<< You must use the backslash
// something
}
}
}
?>
I'm not sure how the structure of Google's API is, and I'm not a real fluent PHP programmer, but you're catching a specific exception type of Exception, with which Google's Google_Auth_Exception may not inherit from.
Therefore, since your try-catch block is looking for an exception that is a member of Exception and the Google_Auth_Exception is perhaps not a member of Exception, then your try catch block will miss it.
Try catching the specific exception. This has happened to me before in many different languages.
Edit
The link you posted inherits its exception from: Google/Auth/Exception
Google/Auth/Exception inherits its exception from: Google/Exception
Google/Exception extends Exception, which may, in this context be the Exception that your class is referring to.
It seems my justification for your try-catch block not catching an exception is completely wrong, but the wisdom could still be true. Try catching the specific exception, then use instanceof to see if PHP recognizes Google_Auth_Exception as a member of Exception.

Should the Exception Class always be caught in try catch?

Is it good coding practice to always catch the base Exception class in a try catch?
try
{
//
// Piece of code
//
}
catch (CustomException $my_ex)
{
// Handle CustomExcepton
}
catch (Exception $other_exceptions)
{
// Handle all other exceptions
}
If so, why?
In PHP you can install a global exception handler.
When needed you can catch exceptions in your code, all unhandled exceptions go to the global exception handler. Depending on your strategie, you decide what to do.
Of course, when you decide to die, a clear error message and a log is appreciated.
In general, if you can recover from a exception, use a try .. catch block, otherwise let the global exception handler do his work, and do not recover.
You should catch only exceptions you now how to handle. Others should bubble up to calling method and some global handler in the end.

Using an Exception to Exit PHP Application

My app has a registered shutdown function and it seems there's some issues with that and my method of using an exception with a try/catch to exit the application (instead of using the exit() method due to FastCGI not liking this).
My problem is that if another exception is thrown in the try/catch block that isn't the ExitApp exception, it causes some unexpected results and the end result is the ExitApp exception isn't caught.
I'm seeing this on PHP 5.3.6, going to test it on another version now, but I'm curious if anyone can immediately point out what's wrong here.
<?php
// Define dummy exception class
class ExitApp extends Exception {}
try {
// Define shutdown function
function shutdown() {
echo "Shutting down...";
throw new ExitApp;
}
register_shutdown_function("shutdown");
// Throw exception!
throw new Exception("EXCEPTION!");
} catch(ExitApp $e) {
echo "Catching the exit exception!";
}
/**
* Expected Result: Uncaught Exception Error and then "Catching the exit exception!" is printed.
* Actual Result: Uncaught Exception Error for "Exception" and then Uncaught Exception Error for "ExitApp" even though it's being caught.
*/
You have wrong expectations from your code. Firstly, if you throw exception in your shutdown function, you will always end up with uncaught exception - shutdown functions are called outside tr/catch block.
Secondly you have no attempt to intercept unknown exception - you are only catching ExitApp types. you may want to try something like this:
try {
//some stuff
} catch(ExitApp $ea) {
//normal exit, nothing to do here
} catch(Exception $e){
//something rather unexpected, log it
}
Your shutdown() function is not even in a try/catch block, so it will never jump down to the catch for this exception type. It is going to run on exit so you will not longer be in that try/catch block.
On a more spiritual, try/catch is not meant for flow control. I'm not quite sure why you're trying to throw this to cause script exit, rather than just calling your own shutdown() method.
Hope that helps.

PHPUnit stub throws exception but isn't allowed to be caught

I'm trying to test a try/catch block using a stub that throws an exception when a certain method create is called. It works fine, the exception is raised, but instead of my application catching it, it stops the execution of the test. What is some better ways to go about doing this.
<?php
// TestCase
$mockDao->expects($this->once())
->method('create')
->will($this->throwException(new \Exception));
$service->addEntity($data);
?>
<?php
// Service
public function addEntity($data)
{
....
try {
...
$this->create($entity); // Test Halts with Exception
...
} catch (Exception $e) {
// Never Gets Called
$this->handleException($e);
}
}
You are throwing \Exception but catching Exception. Is the class that implements addEntity() in a namespace? Does changing it to catch \Exception fix the problem? If not, try changing the test to throw Exception.

Categories