Exception exception in PHP?

I am making a simple card game in PHP. When a user tries to play a map, I want to throw an exception if they can / cannot. Instead of returning a number with a specific value (for example, 1 means "bad card", 2 means not your move ... etc.), I wanted to use individual exceptions. I will catch these exceptions and show the message to the user.

I understand that exceptions are for common errors, but I think this is a good way to develop my program.

Problem: my exceptions are not understood. I have a page called play.php that runs a Game class that has a Round that throws an exception. The play.php page receives a round from the game and makes function calls on it. However, he says that the exception does not fall into the circle.

Is there a quick fix for this? How can I create an exception from my Round class to my play.php page?

// in PLAY.php
try {
    $game->round->startRound($game->players);
} catch (RoundAlreadyStartedException $e) {
    echo $e->getMessage();
}

// in ROUND class
        if (!($this->plays % (self::PLAYS_PER_ROUND + $this->dealer))) {
            try {
                throw new RoundAlreadyStartedException();
            } catch (RoundAlreadyStartedException $e) {
                throw $e;
            }
            return;
        }

I tried to catch, not catch, throw, remodel, etc.

+3
source share
3 answers

I agree with some comments that this is a weird way to achieve what you want to do, however I don't see any real code problems. My test case:

class TestException extends Exception {
}

function raiseTestException() {
    try {
        throw new TestException("Test Exception raised");
    } catch(TestException $e) {
        throw $e;
    }
    return;
}

try {
    raiseTestException();
} catch(TestException $e) {
    echo "Error: " . $e->getMessage();
}

// result: "Error: Test Exception raised";

RoundAlreadyStartedException, , - ?

EDIT: , , ( ):

class TestException extends Exception {
}

class TestClass {

    function raiseTestException() {
        try {
            throw new TestException("Test Exception raised");
        } catch(TestException $e) {
            throw $e;
        }
        return;
    }

}

class CallerClass {

    function callTestCallMethod() {
        $test = new TestClass();
        try {
            $test->raiseTestException();
        } catch(TestException $e) {
            echo "Error: " . $e->getMessage();
        }
    }

}

$caller = new CallerClass();
$caller->callTestCallMethod();

// result: "Error: Test Exception raised";
+6

, , . , , , PHP . , using mynamespace\exceptions\MyException;, . , .

.

+3

Laravel 4.2

Laravel \Exception, , , , Laravel. , \Exception , Exception, .

<?php
namespace Yournamespacehere;

class Exception extends \Exception {
}
+1

Source: https://habr.com/ru/post/1776102/


All Articles