eoinoc
eoinoc

Reputation: 3265

Handling an exception, and only executing code if an exception was not thrown

My script_a.php:

try {
    Class1::tryThis();
}
catch (Exception $e) {
    // Do stuff here to show the user an error occurred
}

Class1::tryThis() has something like:

public function tryThis() {
    Class2::tryThat();
    self::logSuccessfulEvent();
}

The problem is that Class2::tryThat() can throw an exception.

If it does throw an exception, it seems that the line self::logSuccessfulEvent(); still gets executed.

How can I refactor this code so that self::logSuccessfulEvent() only occurs when an exception is not thrown, yet at the same time letting script_a.php know when an exception has been thrown?

Upvotes: 3

Views: 1619

Answers (2)

Jeff Lambert
Jeff Lambert

Reputation: 24661

This function will return whether or not the operation was successful (true = success, false = failure)

public function tryThis() {
   $success = true;

   try {
       Class2::tryThat();
       self::logSuccessfulEvent();
   } catch( Exception $e) {
       $success = false;
   }

   return $success;
}

Upvotes: 7

FtDRbwLXw6
FtDRbwLXw6

Reputation: 28891

What you're describing does not seem to be the case.

Code:

<?php
class Class1 {
    public function tryThis() {
        echo "Class1::tryThis() was called.\n";
        Class2::tryThat();
        self::logSuccessfulEvent();
    }

    public function logSuccessfulEvent() {
        echo "Class1::logSuccessfulEvent() was called.\n";
    }
}

class Class2 {
    public function tryThat() {
        echo "Class2::tryThat() was called.\n";
        throw new Exception('Exception generated in Class2::tryThat()');
    }
}

try {
    Class1::tryThis();
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}

Output:

Class1::tryThis() was called.
Class2::tryThat() was called.
Exception generated in Class2::tryThat()

As you can see, the Class1::logSuccessfulEvent() method is never executed when an exception is generated in Class2::tryThat(), and it shouldn't (won't) either. Exceptions bubble up until they are caught or produce a fatal error. Once an exception is caught, control of the program returns to the code after the catch block. In this particular case, that would mean that control of the program never reaches the logging method.

Upvotes: 2

Related Questions