Jump to content

Need help using try/catch exception handeling


eldan88

Recommended Posts

Hey Guys. I am across this in a book and I am having a hard time understanding how I can try/catch this expception

 

The code below will throw an exception if I add an unit object into Archer or LaserCannon object.

 

Here is a quick example

class UnitException extends  Exception{}

abstract class Unit{



    function AddUnit(Unit $unit){
        throw new UnitException(get_class($this)."is a leaf");
    }
    function removeUnit(Unit $unit){
        throw new UnitException(get_class($this)."is a leaf");

    }

    

    abstract function bombardStrength();


}

class Archer extends  Unit {
    function bombardStrength(){
        return 4;
    }
}




class LaserCannonUnit extends  Unit {
    function bombardStrength(){
        return 44;
    }
}
$laser_cannon = new LaserCannonUnit();
$laser_cannon->AddUnit(New Archer()); // This is not allowed

When I run the client code I get the following error message

 

Fatal error: Uncaught exception 'UnitException' with message 'LaserCannonUnitis a leaf'

 

Can any please help me understand this?? Thanks!

Well, the question is: What do you want to do? What's the purpose of catching the exception?

 

Besides that, always catch specific exceptions, avoid Pokémon Exception Handling as demonstrated above. When you just catch all exceptions, you'll quickly end up swallowing important errors which you never intended to handle.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.