Re: if/else vs. try/catch
Handling exceptions which can be errors.
You can use try catch as a if/else/case if you want to handle exceptions but its not the right way to handle other code flow.
I admit its a bit tricky at first but its a good way of writing code.
Exception by default "bubble" up/back in the execution path and if you didn't handle it at some point it will arise in the object that call that point which its very powerful mechanism that you don't want to write yourself.
try/catch also have a finally clause which promise you execution of code even if you face a situation that you didn't think about in advance.
As a role of thumb in if/case you check values (if($user='zaky')) and it try/catch you check processes (try{upload($file)}catch(notexistException ne){}catch(tobigException et){}).
If you write your design documents with exceptions in mind it will also give you some clue when do you need to use exception.
Example:
The feature: Login page
The processes : the user enter email and password and hit enter
Result: the user redirect to his dashboard.
exceptions:
1. User not exist.
2. User inactive
-- You can use try catch as a if/else/case if you want to handle exceptions but its not the right way to handle other code flow.
I admit its a bit tricky at first but its a good way of writing code.
Exception by default "bubble" up/back in the execution path and if you didn't handle it at some point it will arise in the object that call that point which its very powerful mechanism that you don't want to write yourself.
try/catch also have a finally clause which promise you execution of code even if you face a situation that you didn't think about in advance.
As a role of thumb in if/case you check values (if($user='zaky')) and it try/catch you check processes (try{upload($file)}catch(notexistException ne){}catch(tobigException et){}).
If you write your design documents with exceptions in mind it will also give you some clue when do you need to use exception.
Example:
The feature: Login page
The processes : the user enter email and password and hit enter
Result: the user redirect to his dashboard.
exceptions:
1. User not exist.
2. User inactive
Our newest site for the community: CakePHP Video Tutorials http://tv.cakephp.org
Check out the new CakePHP Questions site http://ask.cakephp.org and help others with their CakePHP related questions.
To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home