{"id":112,"date":"2007-10-26T15:10:18","date_gmt":"2007-10-26T20:10:18","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/2007\/10\/26\/exceptional-behavior\/"},"modified":"2016-11-10T20:29:11","modified_gmt":"2016-11-11T01:29:11","slug":"exceptional-behavior","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2007\/10\/26\/exceptional-behavior\/","title":{"rendered":"Exceptional Behavior"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>One of the new features of MATLAB in R2007b is a more robust way to manage and reporting errors.  We have found that using\r\n         an <tt>MException<\/tt> object, instead of relying on <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/lasterror.html\"><tt>lasterror<\/tt><\/a>, has reduced one sort of coding error.  The reason why the new way is better is because <tt>lasterror<\/tt> is a global state and can be easily corrupted. This can happen in a <tt>try\/catch<\/tt> where you don't want to throw an <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/error.html\"><tt>error<\/tt><\/a> but do something else instead.  However, landing in the <tt>catch<\/tt> updates <tt>lasterror<\/tt> so unless you save its state and later restore it, you may cause some unexpected behavior. In addition, <tt>MException<\/tt> objects allow us to readily augment the information conveyed in an error message. Let's see a little bit about how <tt>MException<\/tt> objects work.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">try and catch E<\/a><\/li>\r\n         <li><a href=\"#4\">Adding cause<\/a><\/li>\r\n         <li><a href=\"#6\">What about error?<\/a><\/li>\r\n         <li><a href=\"#7\">Can You Use This Feature?<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>try and catch E<a name=\"1\"><\/a><\/h3>\r\n   <p>You can generate an MException using new syntax for <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/try.html\"><tt>try\/catch<\/tt><\/a>. As you can see in the following code, you can generate an <tt>MException<\/tt> object now. In the catch segment of code, you see I choose to simply display the message here.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">a = [3 , 2]\r\nb = [1 ; 7]\r\n<span style=\"color: #0000FF\">try<\/span>\r\n    c = a + b;\r\n<span style=\"color: #0000FF\">catch<\/span> myEx\r\n    disp(myEx.message)\r\n<span style=\"color: #0000FF\">end<\/span><\/pre><pre style=\"font-style:oblique\">a =\r\n     3     2\r\nb =\r\n     1\r\n     7\r\nMatrix dimensions must agree.\r\n<\/pre><p>Here's the full display of this <tt>MException<\/tt>.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">myEx<\/pre><pre style=\"font-style:oblique\">myEx =\r\n\r\n\tMException object with properties:\r\n\r\n    identifier: 'MATLAB:dimagree'\r\n       message: 'Matrix dimensions must agree.'\r\n         stack: [4x1 struct]\r\n         cause: {}\r\n<\/pre><p>In addition to the message, it has a message identifier, information about the calling stack, and a cause (another, often underlying <tt>MException<\/tt>).  Get the full details on these properties <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/mexception-class.html\">here<\/a>.\r\n   <\/p>\r\n   <h3>Adding cause<a name=\"4\"><\/a><\/h3>\r\n   <p>To explain more about what's happened, you can add a <tt>cause<\/tt> which is another <tt>MException<\/tt>, to the original <tt>MException<\/tt>.  Here's another way to generate an <tt>MException<\/tt>.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">newME = MException(<span style=\"color: #A020F0\">'Loren:Blog:MExcepExampleAddCause'<\/span>,<span style=\"color: #0000FF\">...<\/span>\r\n    <span style=\"color: #A020F0\">'Vector orientations don''t match.'<\/span>);\r\nmyEx = addCause(myEx,newME)<\/pre><pre style=\"font-style:oblique\">myEx =\r\n\r\n\tMException object with properties:\r\n\r\n    identifier: 'MATLAB:dimagree'\r\n       message: 'Matrix dimensions must agree.'\r\n         stack: [4x1 struct]\r\n         cause: {[1x1 MException]}\r\n<\/pre><p>And to see the added cause, extract it.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">myEx.cause{1}<\/pre><pre style=\"font-style:oblique\">ans =\r\n\r\n\tMException object with properties:\r\n\r\n    identifier: 'Loren:Blog:MExcepExampleAddCause'\r\n       message: 'Vector orientations don't match.'\r\n         stack: [0x1 struct]\r\n         cause: {}\r\n<\/pre><h3>What about error?<a name=\"6\"><\/a><\/h3>\r\n   <p>There is no difference currently between calling <tt>error<\/tt> and throwing an exception directly, since <tt>error<\/tt> already throws an exception internally. <tt>error<\/tt> is essentially implemented as:\r\n   <\/p><pre>  throw(MException(id,msg))<\/pre><p>The reason to throw an exception directly now is to add causes.<\/p>\r\n   <h3>Can You Use This Feature?<a name=\"7\"><\/a><\/h3>\r\n   <p>Do you see yourself using this feature in some of your applications? Post <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=112#respond\">here<\/a> to let me know.\r\n   <\/p><script language=\"JavaScript\">\r\n<!--\r\n\r\n    function grabCode_126cb2e1c0d44c7f8873abd357111b61() {\r\n        \/\/ Remember the title so we can use it in the new page\r\n        title = document.title;\r\n\r\n        \/\/ Break up these strings so that their presence\r\n        \/\/ in the Javascript doesn't mess up the search for\r\n        \/\/ the MATLAB code.\r\n        t1='126cb2e1c0d44c7f8873abd357111b61 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 126cb2e1c0d44c7f8873abd357111b61';\r\n    \r\n        b=document.getElementsByTagName('body')[0];\r\n        i1=b.innerHTML.indexOf(t1)+t1.length;\r\n        i2=b.innerHTML.indexOf(t2);\r\n \r\n        code_string = b.innerHTML.substring(i1, i2);\r\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\r\n\r\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \r\n        \/\/ in the XML parser.\r\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\r\n        \/\/ doesn't go ahead and substitute the less-than character. \r\n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\r\n\r\n        author = 'Loren Shure';\r\n        copyright = 'Copyright 2007 The MathWorks, Inc.';\r\n\r\n        w = window.open();\r\n        d = w.document;\r\n        d.write('<pre>\\n');\r\n        d.write(code_string);\r\n\r\n        \/\/ Add author and copyright lines at the bottom if specified.\r\n        if ((author.length > 0) || (copyright.length > 0)) {\r\n            d.writeln('');\r\n            d.writeln('%%');\r\n            if (author.length > 0) {\r\n                d.writeln('% _' + author + '_');\r\n            }\r\n            if (copyright.length > 0) {\r\n                d.writeln('% _' + copyright + '_');\r\n            }\r\n        }\r\n\r\n        d.write('<\/pre>\\n');\r\n      \r\n      d.title = title + ' (MATLAB code)';\r\n      d.close();\r\n      }   \r\n      \r\n-->\r\n<\/script><p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_126cb2e1c0d44c7f8873abd357111b61()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n            the MATLAB code \r\n            <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\r\n      Published with MATLAB&reg; 7.5<br><\/p>\r\n<\/div>\r\n<!--\r\n126cb2e1c0d44c7f8873abd357111b61 ##### SOURCE BEGIN #####\r\n%% Exceptional Behavior\r\n% One of the new features of MATLAB in R2007b is a more robust way to manage\r\n% and reporting errors.  We have found that using an\r\n% <https:\/\/www.mathworks.com\/access\/helpdesk\/help\/techdoc\/ref\/mexception.html |MException|>\r\n% object, instead of relying on \r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/lasterror.html |lasterror|>,\r\n% has reduced one sort of coding error.  The reason why the new way is better\r\n% is because |lasterror| is a global state and can be easily corrupted.\r\n% This can happen in a |try\/catch| where you don't want to throw an \r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/error.html |error|>\r\n% but do something else instead.  However, landing in the |catch| updates\r\n% |lasterror| so unless you save its state and later restore it, you may\r\n% cause some unexpected behavior.\r\n% In addition, |MException| objects\r\n% allow us to readily augment the information conveyed in an error message.\r\n% Let's see a little bit about how |MException| objects work.\r\n%% try and catch E\r\n% You can generate an MException using new syntax for \r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/try.html |try\/catch|>.  \r\n% As you can see in the following code, you can generate an |MException|\r\n% object now. In the catch segment of code, you see I choose to simply\r\n% display the message here.\r\na = [3 , 2]\r\nb = [1 ; 7]\r\ntry\r\n    c = a + b;\r\ncatch myEx\r\n    disp(myEx.message)\r\nend\r\n%%\r\n% Here's the full display of this |MException|.\r\nmyEx\r\n%%\r\n% In addition to the message, it has a \r\n% <https:\/\/www.mathworks.com\/access\/helpdesk\/help\/techdoc\/matlab_prog\/bq9l448-1.html#bq9tdlq-1 message identifier>, \r\n% information about the calling stack, and a cause (another, often\r\n% underlying |MException|).  Get the full details on these properties\r\n% <https:\/\/www.mathworks.com\/access\/helpdesk\/help\/techdoc\/matlab_prog\/bq9l448-1.html#bq9l5ap-1 here>.\r\n%% Adding cause\r\n% To explain more about what's happened, you can add a |cause| which is\r\n% another |MException|, to the original |MException|.  Here's another way\r\n% to generate an |MException|.\r\nnewME = MException('Loren:Blog:MExcepExampleAddCause',...\r\n    'Vector orientations don''t match.');\r\nmyEx = addCause(myEx,newME)\r\n%%\r\n% And to see the added cause, extract it.\r\nmyEx.cause{1}\r\n%% What about error?\r\n% There is no difference currently between calling |error| and throwing an\r\n% exception directly, since |error| already throws an exception internally.\r\n% |error| is essentially implemented as:\r\n%   \r\n%    throw(MException(id,msg))\r\n% \r\n% The reason to throw an exception directly now is to add causes. \r\n%% Can You Use This Feature?\r\n% Do you see yourself using this feature in some of your applications?\r\n% Post <https:\/\/blogs.mathworks.com\/loren\/?p=112#respond here> to let me know.\r\n\r\n\r\n##### SOURCE END ##### 126cb2e1c0d44c7f8873abd357111b61\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      One of the new features of MATLAB in R2007b is a more robust way to manage and reporting errors.  We have found that using\r\n         an MException object, instead of relying on... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2007\/10\/26\/exceptional-behavior\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[16,6],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/112"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/comments?post=112"}],"version-history":[{"count":2,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/112\/revisions"}],"predecessor-version":[{"id":2107,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/112\/revisions\/2107"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=112"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=112"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=112"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}