eldan88 Posted August 13, 2014 Share Posted August 13, 2014 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! Quote Link to comment https://forums.phpfreaks.com/topic/290437-need-help-using-trycatch-exception-handeling/ Share on other sites More sharing options...
Solution gristoi Posted August 13, 2014 Solution Share Posted August 13, 2014 try{ $laser_cannon->AddUnit(New Archer()); // This is not allowed }catch(Exception $e){ // do what you need here } Quote Link to comment https://forums.phpfreaks.com/topic/290437-need-help-using-trycatch-exception-handeling/#findComment-1487698 Share on other sites More sharing options...
eldan88 Posted August 13, 2014 Author Share Posted August 13, 2014 Ahh okay. I was thinking there was a way to do it inside the abstract class. But that makes sense. Thank you Quote Link to comment https://forums.phpfreaks.com/topic/290437-need-help-using-trycatch-exception-handeling/#findComment-1487699 Share on other sites More sharing options...
Jacques1 Posted August 13, 2014 Share Posted August 13, 2014 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. Quote Link to comment https://forums.phpfreaks.com/topic/290437-need-help-using-trycatch-exception-handeling/#findComment-1487724 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.