<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	>

<channel>
	<title>unitstep.net &#187; exceptions</title>
	<atom:link href="http://unitstep.net/blog/category/exceptions/feed/" rel="self" type="application/rss+xml" />
	<link>http://unitstep.net</link>
	<description>the home of peter chng</description>
	<pubDate>Sun, 05 Oct 2008 17:42:16 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.6.2</generator>
	<language>en</language>
			<item>
		<title>CakePHP and error/exception handling</title>
		<link>http://unitstep.net/blog/2008/05/11/cakephp-and-errorexception-handling/</link>
		<comments>http://unitstep.net/blog/2008/05/11/cakephp-and-errorexception-handling/#comments</comments>
		<pubDate>Sun, 11 May 2008 18:40:08 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
		
		<category><![CDATA[PHP]]></category>

		<category><![CDATA[cakephp]]></category>

		<category><![CDATA[development]]></category>

		<category><![CDATA[exceptions]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=321</guid>
		<description><![CDATA[
I&#8217;m currently using CakePHP and finding it to be quite useful.  The &#8220;automagic&#8221; handling of tables is useful for basic relationships, though more complicated setups usually require manual work.  The MVC implementation has also clearly drawn inspiration from Ruby on Rails, which may be advantageous to some, though this has no bearing on [...]]]></description>
			<content:encoded><![CDATA[<p class="image align-right"><img src="http://unitstep.net/wordpress/wp-content/uploads/2008/05/cakephp.png" alt="Copyright CakePHP" title="cakephp" width="150" height="139" /></p>
<p>I&#8217;m currently using <a href="http://cakephp.org/">CakePHP</a> and finding it to be quite useful.  The &#8220;automagic&#8221; handling of tables is useful for basic relationships, though more complicated setups usually require manual work.  The MVC implementation has also clearly drawn inspiration from <a href="http://www.rubyonrails.org/">Ruby on Rails</a>, which may be advantageous to some, though this has no bearing on me.  Though there are a few things that nag me about CakePHP (such as lack of a good testing suite, though that&#8217;s supposedly <a href="http://bakery.cakephp.org/articles/view/testing-models-with-cakephp-1-2-test-suite">fixed in 1.2</a>, which really should be marked as version 2.0), overall it&#8217;s a great framework that adds badly-needed structure to <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> and has saved me time.</p>
<p>One thing I&#8217;d like to see, however, is a proper exception handling model.  I realize this would <a href="http://gophp5.org/">require making it <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> 5-only</a>, but in my opinion, <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> 5 adds some sorely-need features, such as the aforementioned exception handling model and a class/object system more in line with other languages.</p>
<h3>Signaling intent</h3>
<p>I&#8217;ve written about the <a href="/blog/2007/11/25/exception-handling-in-javascript/">benefits of exception handling</a> before, so I won&#8217;t delve into those details again.  In short, using exceptions is a better way for a method to signal to a caller that something went wrong rather than just returning a special/reserved value as an error code.</p>
<p>In particular, saving of models would benefit from this.  Currently, if you want to check if the model was saved properly, you have to do something like this:</p>
<pre><code>if ($this-&gt;ModelName-&gt;save($this-&gt;data))
{
  // Model saved properly, can continue normally here.
  ...
}
else
{
 // Model did not save properly.
}</code></pre>
<p>It&#8217;s a little bit kludgy, but isn&#8217;t actually that bad since Cake simplifies form validation a lot with the <acronym class="uttInitialism" title="HyperText Markup Language">HTML</acronym> helper in views.  You can simply put something like <code>$html-&gt;tagErrorMsg('Post/title', 'Title is required.')</code> in your view to display that error message when a particular field does not validate.  This removes a lot of the tedium out of making your forms return proper error messages in situations with bad input.</p>
<h3>Exceptional cases</h3>
<p>However, in some situations you might want to execute your own logic when a call to <code>Model::save()</code> fails.  In this case, having that method throw a proper exception would allow the error to be propagated to the controller nicely and would remove the need to make a call to <code>Model::invalidFields()</code> to get the reason.</p>
<p>Coming from a Java background, this makes more sense to me, since I consider its exception handling model to be one of the language&#8217;s strong points.  It has numerous benefits to improving readability and maintainability of code.</p>
<p>However, there are some drawbacks, since this requires the use of <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> 5.  As CakePHP is designed to be <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> 4 and 5 compatible, exception handling is really not an option.  However, since <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> 4 is so old, I&#8217;d eventually like to see a <a href="http://gophp5.org/">move to <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> 5</a>, especially for its better OOP model and exception handling.  Additionally, <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> 6 is just around the corner, so I don&#8217;t really see a need to stick with <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> 4 for that much longer.</p>
<p>Additionally, if you&#8217;re just saving one model (as the result of a form submission) it doesn&#8217;t really make sense, nor is it necessary, to have exception handling since CakePHP already takes care of displaying error message for the invalid fields:</p>
<pre><code>// Controller:
...
if ($this-&gt;Post-&gt;save($this-&gt;data))
{
  $this-&gt;flash('Your post has been saved.','/posts');
}
...

// View:
...
&lt;?php echo $html-&gt;input('Post/title', array('size' =&gt; '40'))?&gt;
&lt;?php echo $html-&gt;tagErrorMsg('Post/title', 'Title is required.') ?&gt;
...</code></pre>
<p>In the above example, taken from <a href="http://manual.cakephp.org/view/326/the-cake-blog-tutorial">CakePHP&#8217;s own blog tutorial</a>, you don&#8217;t really need exception handling since the appropriate actions are automatically handling by Cake.  If the save succeeds, a positive message will be displayed and the user forwarded on.  Otherwise, the controller proceeds to render the given view, where <code>$html-&gt;tagErrorMsg</code> displays the given error message if the associated field was marked as invalid by the model during the save attempt.</p>
<p>For more complicated situations where you&#8217;re saving multiple related models in a single controller action, exception handling would be helpful in reducing the number of branches, since you wouldn&#8217;t need to have so many <code>if ... else</code> blocks muddling up the flow of the code.  However, it&#8217;s not straightforward to integrate this into Cake, since for most of the time, people won&#8217;t need the exception handling capability if they&#8217;re just doing a simple save as outlined above. </p>
<p>The easiest way I see of accomplishing this is to define your own method that wraps around the existing <code>Model::save()</code> method so that proper exceptions can be thrown.  This would, of course, create confusion as then there would be <em>two</em> &#8217;save&#8217; methods. </p>
<p>All things considered, Cake is still a strong framework, so I will continue using it.  For all the slight concerns I have, it&#8217;s still very much beneficial to me.  If there&#8217;s one more thing I could ask for from Cake though, it would be for better documentation!  Maybe I should start contributing&#8230;</p>
<hr/>Copyright &copy; 2008 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2008/05/11/cakephp-and-errorexception-handling/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Exception handling in JavaScript</title>
		<link>http://unitstep.net/blog/2007/11/25/exception-handling-in-javascript/</link>
		<comments>http://unitstep.net/blog/2007/11/25/exception-handling-in-javascript/#comments</comments>
		<pubDate>Mon, 26 Nov 2007 01:54:00 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
		
		<category><![CDATA[JavaScript]]></category>

		<category><![CDATA[exceptions]]></category>

		<category><![CDATA[guides]]></category>

		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://unitstep.net/blog/2007/11/25/exception-handling-in-javascript/</guid>
		<description><![CDATA[Exception handling is a topic that may not be well-understood by some web developers, depending on what languages they have the most experience in.  In particular, PHP, one of the most common server-side languages for web development, did not have support for exception handling until version 5.  In the four years between the [...]]]></description>
			<content:encoded><![CDATA[<p>Exception handling is a topic that may not be well-understood by some web developers, depending on what languages they have the most experience in.  In particular, <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym>, one of the most common server-side languages for web development, did not have support for exception handling until <a href="http://www.php.net/exceptions">version 5</a>.  In the four years between the release of PHP4 and PHP5, the language became increasingly popular among developers, and as a result, a lot of code was written without exception handling in mind.  The situation did not even improve much with the release of PHP5, since PHP5 was meant to be backwards-compatible with code developed for PHP4.  Three years later, there are still <a href="http://www.gophp5.org/">movements</a> to get developers to transition to a purely-PHP5 model.</p>
<p>Some of this may have transferred over to JavaScript, a language that is already poorly understood and often implemented even worse.  It is often hard to find well-written, maintainable JavaScript code, as it is often left as an afterthought in a project or otherwise not given much consideration, having been delegated to the realm of popup scripts and mouse-overs.  While exception handling may be overkill for a lot of JavaScript applications, many do not even know of JavaScript&#8217;s exception-handling capabilities.  In this article, I&#8217;ll give a brief overview of exception handling and some recommendations on how to use it in JavaScript to improve the readability of code. </p>
<h2>Exceptional conditions</h2>
<p>I won&#8217;t go too in-depth about the <a href="http://java.sun.com/docs/books/tutorial/essential/exceptions/advantages.html">merits of using exception handling</a> but will instead just give a brief overview.  (While there are some drawbacks, these apply more to the Java language rather than JavaScript)</p>
<p>The main reason for using exceptions is to have a separate channel for communicating errors.  Without this, you must communicate error conditions using the function itself. Consider a function that performs mathematical division:</p>
<pre><code>function divide(dividend, divisor)
{
  var quotient = dividend/divisor;
  return quotient;
}</code></pre>
<p>Division is a fairly simple arithmetic operation, but of the four basic operations it is the only one that has limits on its arguments: the divisor (the term you divide by) cannot be zero, since <a href="http://en.wikipedia.org/wiki/Division_%28mathematics%29">division by zero is undefined.</a>  So, how should you handle cases where the supplied arguments result in division by zero?  (The situation is very likely in an application accepting user input)</p>
<p>Without using exceptions, you have a few options, each of which has its own weaknesses.  Firstly, you could choose not to return <em>anything</em> and just <code>alert()</code> the user of the error.  This isn&#8217;t good since when you call the <code>divide()</code> function, you expect a result, not a warning message.</p>
<p>Secondly, you could choose to return a special &#8220;error code&#8221; indicating that there was a division by zero.  But this creates another problem - what exactly <em>do</em> you return when something goes wrong?  In this case, the only error case is division by zero - since JavaScript is a weakly-typed language, you could just return <code>false</code> on this error, but then in the calling code you&#8217;d have to check if <code>divide()</code> equaled <code>false</code> before using it, probably using the <a href="http://www.webreference.com/js/column26/stricteq.html">strict equality operator</a>.  As you can see, things get messy fast. </p>
<p>Alternatively, you could just check the inputs/arguments every time before you called the function.  However this is clumsy, and adds another layer of complexity where something could go wrong.  </p>
<h2>Another way of doing things</h2>
<p>As mentioned before, exception handling adds a side channel of sorts strictly for communicating errors.  By doing this, it allows for the interruption of program flow for the purpose of dealing with the exception or error situation.  Using exceptions, you would re-write the function above like this:</p>
<pre><code>function divide(dividend, divisor)
{
  if (0 == divisor) {
    throw new Error("Bzlorg! Cannot divide by zero.");
  }

  var quotient = dividend/divisor;
  return quotient;
}</code></pre>
<p>Here we are checking if the divisor equals zero - signifying an invalid input value - and then throwing an exception if this is the case.  How is this different than returning an error code?</p>
<p>The main difference is in the <em>control flow</em> of the program; using exceptions causes a change in the program flow.  In the above example, if the divisor equals zero, the execution of the function stops there and returns to the calling code with the throw exception.  The subsequent statements calculating the quotient and returning will not be executed.  Here&#8217;s an example of how you&#8217;d call the <code>divide</code> function.</p>
<pre><code>try {
  var dividend = 3;
  var divisor = 0;

  var quotient = divide(dividend, divisor);

  alert("The answer is " + quotient);
}
catch (e) {
  alert(e.message);
}</code></pre>
<p>With exceptions, you enclose code that could throw an exception with a <code>try</code> block.  This signifies to the interpreter (in the case of JavaScript) that you will be executing code (in this case, calling a function) that <em>could</em> throw an exception as a result of some error condition.  Thus you are <code>try</code>ing to do something - but as in real life, things may go wrong.</p>
<p>In this example, everything works until the line calling <code>divide</code>.  Since <code>divide</code> throws an exception with the input values supplied, flow will be directed to the <code>catch</code> block.  All <code>try</code> blocks must be followed with a <code>catch</code> block, with the variable in the parentheses specifying the variable to hold the thrown exception object.  In the code above, we merely alert the user to the problem - the message &#8220;Bzlorg! Cannot divide by zero&#8221; is displayed - in a real program you most likely would want to do handle the error differently depending on the context - but that&#8217;s a whole different topic.</p>
<p>If, however, you executed the code with valid values and no exceptions were thrown, once the program had got to the end of the <code>try</code> block it would jump over the following <code>catch</code> block and the user would be alerted with the correct answer.  Code within a <code>catch</code> block is <em>only</em> executed in the event that an exception is thrown.</p>
<h3>Differences with Java</h3>
<p>Since Java is an extremely popular language and one that also uses a similar exception handling model, it would be prudent to discuss some of the differences and similarities with it and JavaScript.</p>
<ol>
<li>
<h4><del>No multiple catch blocks with JavaScript</del></h4>
<p><del>This is perhaps the biggest difference.  If you&#8217;re familiar with Java you&#8217;ll know that different exception objects can be thrown during execution (all subclasses of the root/parent <code>Exception</code> class defined by Java), each signifying different error conditions.  You catch each of them separately by using separate catch blocks, each specifying a particular class or parent class.  However, with JavaScript, as you might have noticed from the code above, there can only be one catch block and thus there&#8217;s no need to specify the exception class. </del></p>
<p><del>If, however, you want the granularity of working with different exception classes, you&#8217;ll have to use the <code>instanceof</code> operator within a catch block, like this:</del></p>
<pre><code>try {
  ...
}
catch (e) {
  if (e instanceof RangeError) {
    ...
  }
  else if (e instanceof TypeError) {
    ...
   }
}</code></pre>
<p><del>It&#8217;s not as elegant as having multiple catch blocks, but it&#8217;s one way to deal with multiple exception types.</del></p>
<h4>Correction:</h4>
<p>It appears I was mistaken.  In JavaScript, you can indeed have <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Exception_Handling_Statements:try...catch_Statement#The_catch_Block">multiple catch blocks</a>, as seen in the <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide">Core JavaScript 1.5 Guide</a> from the Mozilla Developer Center.  My initial example above is still valid syntactically, but this way may be more appealing.  An example is as follows:</p>
<pre><code>try {
  ...
}
catch (e if e instanceof RangeError) {
  ...
}
catch (e if e instanceof TypeError) {
  ...
}
catch (e) {
  // General catch-all block.
  ...
}</code></pre>
<p>It just goes to show that when you think you know something, you probably don&#8217;t!  This is part of why I like JavaScript (and by extension, programming); there&#8217;s always more to learn and experience to be gained.</p>
</li>
<li>
<h4>Exception types</h4>
<p>The discussion of exception types brings us to another point - the different exception types in JavaScript.  JavaScript defines some <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Error">built-in exception</a> types, all based off the parent <code>Error</code> object.  These should suffice for most situations where you&#8217;re checking user input (the most common use), but if you&#8217;re developing a complex application you may want to define your own.  </p>
<p>In that situation, things get a little tricky, especially if you&#8217;re coming from Java.  Despite the outward similarity, JavaScript does not uses classes like Java, but instead uses a <a href="http://en.wikipedia.org/wiki/Prototype-based_programming">prototype-based approach</a> where inheritance comes from existing objects.  In this respect, things can get complicated as there are debates on <a href="http://www.sitepoint.com/blogs/2006/01/17/javascript-inheritance/">what the best way to inherit from objects</a> is and to that degree, a few JavaScript libraries have been written to facilitate the extending of objects in JavaScript.  These points are beyond the scope of this article, but I thought I&#8217;d just point you in the right direction.</p>
<p>Interestingly, you can also <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Exception_Handling_Statements:throw_Statement">throw many different</a> types of expressions, and are not limited to the built-in exception types.  For example, <code>throw false;</code> and <code>throw "Hello World";</code> are valid statements, but in my opinion, it doesn&#8217;t make much sense to throw any type of expression just because you can.  Using the built-in exception types (or defining your own) is a better practice, though throwing just String expressions might be alright in some situations.
</li>
<li>
<h4>Runtime errors</h4>
<p>During execution, you code may trigger runtime errors within JavaScript - for example, when trying to reference a property on a non-existent object.  These will also result in a new <code>Error</code> object being thrown, even though you did not define this throw in your code.  If this happens within a try block, the exception will subsequently be caught in the following catch block, and if you&#8217;re not expecting this error you may miss it.  (If, for example, you&#8217;re only looking for specific exception object types)</p>
<p>This can create problems with some of the JavaScript debuggers out there like <a href="http://www.getfirebug.com">Firebug</a>.  Since the runtime exception is being caught, Firebug will not be able to catch it (it is prevented from &#8220;filtering&#8221; up), so you may not be able to locate the source of your error if you&#8217;re relying on the debugger.  </p>
<p>My recommendation is thus to ensure your code runs properly under normal conditions.  Only then should you start using exceptions and try-catch statements.  This will ensure that no unexpected runtime exceptions get caught.  (The runtime errors are analogous to the unchecked runtime exceptions of Java in that they are not normally caught)
</li>
</ol>
<h3>Summing it up</h3>
<p>The whole point of using exceptions is not to make your code &#8220;work&#8221; better - anything that can be accomplished with exceptions can most likely be done without it, with just the same end result.  The point is to make your code more readable, manageable and flexible.  By using exceptions you get rid of having to use cumbersome &#8220;error codes&#8221;, the values of which you may forget later.  You also get more flexibility with how you handle errors.  You need not handle the error right in the function where it occurs - you can throw an exception to the calling code and handle the error there - or, alternatively, you could let the exception bubble up to a higher-level and handle all errors there.  It really depends on your needs, but using exceptions allows for this to be implemented more readily.</p>
<p>Though exceptions may seem like overkill for JavaScript and despite the limitations of its exception handling model as compared to that of Java&#8217;s, there are still some benefits to using exceptions, especially for complex JavaScript applications that you may implement to improve the interactivity of your site. </p>
<h4>Changes/Fixes</h4>
<ul>
<li><strong>2007-12-06</strong>: Changed <code>throw new Exception(...)</code> to correct statement of <code>throw new Error(...)</code>.</li>
<li><strong>2008-01-08</strong>: Fixed incorrect assertion of &#8220;No Multiple Catch Blocks&#8221; in JavaScript; added remarks about being able to throw any type of expression.</li>
</ul>
<hr/>Copyright &copy; 2008 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2007/11/25/exception-handling-in-javascript/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
