tag:blogger.com,1999:blog-7988792589954261688.post6389619455432075905..comments2024-03-08T12:36:26.976+03:00Comments on CodeBuild: 15 Best Practices for Exception HandlingCBhttp://www.blogger.com/profile/13504212299235753253noreply@blogger.comBlogger38125tag:blogger.com,1999:blog-7988792589954261688.post-18830304447371012192016-02-06T15:11:44.430+02:002016-02-06T15:11:44.430+02:00This comment has been removed by a blog administrator.Anonymoushttps://www.blogger.com/profile/17896342774792587644noreply@blogger.comtag:blogger.com,1999:blog-7988792589954261688.post-21328103399109889442016-02-06T14:21:01.609+02:002016-02-06T14:21:01.609+02:00This comment has been removed by a blog administrator.Anonymoushttps://www.blogger.com/profile/17896342774792587644noreply@blogger.comtag:blogger.com,1999:blog-7988792589954261688.post-40432277721634931232015-12-30T12:42:59.646+02:002015-12-30T12:42:59.646+02:00This comment has been removed by a blog administrator.hitesh kumarhttps://www.blogger.com/profile/05867507126640156133noreply@blogger.comtag:blogger.com,1999:blog-7988792589954261688.post-84443359118576435582015-12-14T21:43:04.781+02:002015-12-14T21:43:04.781+02:00http://stackoverflow.com/questions/34275153/throw-...http://stackoverflow.com/questions/34275153/throw-the-same-exception-if-it-is-not-handled-or-construct-a-new-exceptionKoray Tugayhttps://www.blogger.com/profile/02753700062310619299noreply@blogger.comtag:blogger.com,1999:blog-7988792589954261688.post-57859133482221215982015-11-05T15:29:02.679+03:002015-11-05T15:29:02.679+03:00Nice Article and see java exception facts
http:/...Nice Article and see java exception facts <br /><br />http://www.javaproficiency.com/2015/02/interesting-facts-in-exception-handling.htmlAnmolhttps://www.blogger.com/profile/12378063691630709751noreply@blogger.comtag:blogger.com,1999:blog-7988792589954261688.post-83846179965784538462015-07-24T08:39:22.094+03:002015-07-24T08:39:22.094+03:00I accepted this method.loop process making a lot a...I accepted this method.loop process making a lot a time.How to reduce the time interval?aaidanhttp://www.trainingintambaram.in/web-designing-training-in-chennai.htmlnoreply@blogger.comtag:blogger.com,1999:blog-7988792589954261688.post-39589734859551332312013-06-10T23:39:00.548+03:002013-06-10T23:39:00.548+03:00#12, in a lot of cases the loop is used by batch j...#12, in a lot of cases the loop is used by batch jobs. You will like to have try/catch inside the loop in order to maximize the processing. Lots of the system will skip the failed one and continue on.Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-7988792589954261688.post-55789998642619899162013-04-10T17:56:03.740+03:002013-04-10T17:56:03.740+03:00I just stumbled over this 1-year-old post, still a...I just stumbled over this 1-year-old post, still a google top result when searching for exception best practices.<br /><br />For me, there are two main guidelines for exceptions:<br /><br />A) I throw an exception if my method did not fulfill its contract. By returning normally without exception, I tell my method's caller that the job has been completely done.<br /><br />B) Catching an exception means that I warrant the program can reasonably continue from this point, whatever situation caused the exception. Typically, the next statements depend on the previous ones, so how can you continue if they failed somehow. Typically, I only catch exceptions around top-level actions.<br /><br />From these guidelines, I disagree with some of your best practices (or the reasons you give for them).<br /><br />I support #4, but for different reasons. If you catch just a given subclass of Exception, it's easier to analyze its possible causes in the try-catch surrounded block and to warrant that continuing the program makes sense. But I doubt that there is a measurable performance difference between more or less specific exception classes in catch clauses.<br /><br />#5 depends on what the "contract" defines. If e.g., not finding an element in a list is considered a normal situation and thus documented in the Javadocs, then returning null is perfectly valid and throwing an exception is not. If, on the other hand, the contract assumes that a matching object will be present, then you must throw an exception, and that can be a NullPointerException (not the best choice, but still legitimate).<br /><br />#6 recommends against rethrowing exceptions, and this because of performance reasons. Never let (often poorly understood) performance concerns guide your software style. When exceptions cause significant performance issues, you probably missed my guideline B). Rethrowing or wrapping and rethrowing exceptions can be <br /><br />#8 defines Warn, Info and Debug types of exceptions. That's logging and not exceptions, because in these cases the methods probably fulfilled their contract asking for a normal return without exception.<br /><br />#13 strongly contradicts my guideline B). I can't believe that every 5 or 10 lines of code there's a point where the program can continue useful work, even if the previous steps failed. The very concept of exceptions aims to make code more readable by having less error handling overhead.<br /><br />Best regards<br />-- RalfAnonymousnoreply@blogger.comtag:blogger.com,1999:blog-7988792589954261688.post-26459410429760069112012-03-07T16:04:34.819+02:002012-03-07T16:04:34.819+02:00Great point, reading up always is useful. However,...Great point, reading up always is useful. However, not all frameworks exhibit "best practices". For instance, some Microsoft tools and libraries (e.g.: MSTest, Entity Framework) tend to be quite behind community accepted best practices and thus their guidance can be sub-optimal.Peter Zsoldoshttp://zsoldosp.blogspot.comnoreply@blogger.comtag:blogger.com,1999:blog-7988792589954261688.post-70822185247299379072012-03-03T12:05:24.942+02:002012-03-03T12:05:24.942+02:00Best practice is read Framework Design Guidelines....Best practice is read Framework Design Guidelines.<br /><br />I don't agree with first practice. In general it will much easier and understandable code with exceptions in comparison with return codes (witch is C-style). Return codes can be used, for example on critical way of high load app.тмиhttps://www.blogger.com/profile/12687297686129555871noreply@blogger.comtag:blogger.com,1999:blog-7988792589954261688.post-46228220135748644592012-02-09T09:06:55.607+02:002012-02-09T09:06:55.607+02:00+1 for Craig's advice about when one should ca...+1 for Craig's advice about when one should catch Exceptions<br /><br />The logging/displaying of the generic exception could make sense, but only at the outermost place (the application unhandled exception event handlerj), but one has to be careful where is it logged/displayed - you don't want to reveal too much information to the user when your production website crashes...Peter Zsoldoshttp://zsoldosp.blogspot.comnoreply@blogger.comtag:blogger.com,1999:blog-7988792589954261688.post-30248097685500881192012-02-08T19:49:31.172+02:002012-02-08T19:49:31.172+02:00I agree. I discourage my .NET students from tryin...I agree. I discourage my .NET students from trying to catch specific exceptions since it is often hard to predict what exceptions may arise. I only advocate having specific exception handlers when there needs to be specific actions taken for a specific exception type. <br /><br />I encourage them to just use catch (Exception ex) and then they can log the type of the exception, the exception message and indicate what operation failed so that the user has context. <br /><br />In most cases logging/displaying what happened (operation x failed) and why it happened (exception type and message) is the best and most practical strategy.Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-7988792589954261688.post-38165557333805285472012-02-06T23:44:01.347+02:002012-02-06T23:44:01.347+02:00Another guideline that I recommend is to avoid wri...Another guideline that I recommend is to avoid writing algorithms based on exception handling. For example in this <a href="http://stackoverflow.com/questions/5237909/how-to-force-filesystemwatcher-to-wait-till-the-file-downloaded" rel="nofollow">thread</a> on stackoverflow forum, the algorithm in the answer proposed by ukhardy uses the IOException in the while loop.Akram El Assashttp://aelassas.free.frnoreply@blogger.comtag:blogger.com,1999:blog-7988792589954261688.post-67353158355720487812012-02-05T03:50:01.712+02:002012-02-05T03:50:01.712+02:00I once worked on a project where the manager had c...I once worked on a project where the manager had coded an exception-catcher which completely obscured where the exception had occurred.<br />Don't do that ;-)<br /><br />(This is the same guy who coded error message "Parameter error", took me 2 hours to find when he was away one day..)<br /><br />I would add to (2) "and unique" (!)<br />Further than that, I'd give each a unique code, recorded on a separate database, pointing to further useful information.<br /><br />If you catch and exception with a state-word (of bit-indicators), it may be useful to interpret states in a way that can be passed back to the caller. Dropping the state-word & obscuring it is not good practice.<br /><br />If you have exceptions which are common but harmless, it's as well to divert the (after reporting!) to a "harmless" bucket.<br />A example of this is collecting unfulfilled links in a mapping or linkage. The advantage of this is that if a code change produces a new linking exception, it's easily spotted.Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-7988792589954261688.post-54550782371568653642012-02-03T14:35:04.784+02:002012-02-03T14:35:04.784+02:00Having come to python from a .NET/Java background,...Having come to python from a .NET/Java background, I was rather frustrated with the lack of specific exceptions and the language's reliance on the error message. <br /><br />First, I prefer to put concrete details into exception messages (e.g.: instead of "Invalid Number" I prefer to say "XII could not be parsed to a number"), which then requires regexp pattern matching or contains, which is a great tool, but in case of exceptions I'd rather be sure. Also, I've seen a number of cases of unit test suites that relied on exception messages failing when run on non-US locales.<br /><br />While in certain situations, you might only care about IOExceptions, in a CMS document editing scenario you might provide different error messages to your users depending on *why* you couldn't open the file - non-existent files and not being able to obtain exclusively for writing are two different things.<br /><br />But I do agree that exception hierarchies just for the sake of it is a bad idea - only do these a) if you are writing a framework b) when you actually need it.Peter Zsoldoshttp://zsoldosp.blogspot.comnoreply@blogger.comtag:blogger.com,1999:blog-7988792589954261688.post-76418948176329021812012-02-02T23:46:56.533+02:002012-02-02T23:46:56.533+02:00My experience is somewhat different.
It is good p...My experience is somewhat different.<br /><br />It is good practice to manually check input for each method, and not to proceed with invalid data. Valid data should never generate exceptions - exceptions are a lot more expensive than normal returns. As a consequence, exceptions should almost exclusively be used to signal irrecoverable problems in application code.<br /><br />The situation is slightly different for library code. A library designer has no idea of how and if the library's clients will want to proceed when a specific abnormal situation occurs. It's also difficult for him to predict all usage patterns, and it is almost never feasible to restrict the library use to allow only valid usage. This leaves a lot of space for incorrect calls, so the library code must signal conditions which are abnormal to the library but may be recoverable for users.<br /><br />For instance send a select statement to a database in order to test for the database's existence is an example of incorrect usage, but the situation, although abnormal for the database, is perfectly recoverable for the caller, and the best way for the database driver to signal the abnormality is an exception. If, instead of reading from a database, you try to read from a hash table, not checking for a key's presence or for null on return is plain stupid, and a very bad way to use exceptions. If you are in library code yourself, and you were asked by client code to look up the value a key which doesn't exist, it is again an exception which is the most adequate way of signaling the abnormality to the caller.<br /><br />This means that exceptions received from libraries are either recoverable, in which case you simply handle the exception and continue, or they are irrecoverable, in which case there's not much use in interpreting them.<br /><br />So what do I usually do? I have a try/catch around the entire method body for all methods, and smaller try/catch blocks around specific statements or statement groups from which I expect exceptions which are recoverable. The outer try/catch just throws the exception up the call stack - if any exception reaches its catch, it is definitely one from which I can't recover locally, so it makes no sense to parse it. This also allows me to easily transform Exception into RuntimeException in Java, which helps with the checked exceptions problem mentioned above. At the top of every call stack there's a central dispatch point in the application where all exceptions from which there was no recovery land. That place simply logs them, and exits or restarts, depending on what's adequate for the given type of application.<br /><br />What are the benefits? Exceptions are handled in a very uniform way, but with minimal overhead, both in terms of runtime effort and programming effort.Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-7988792589954261688.post-54107065233791395552012-02-02T23:10:20.676+02:002012-02-02T23:10:20.676+02:00Great little piece! I'm currently doing a pers...Great little piece! I'm currently doing a personal project that will be done by 2016. Gonna make me Millions lol! I'll have to do Exception handling totally properly for once! Bookmarked this! It has everything I want in Exception Handling that I've a history of forgetting!Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-7988792589954261688.post-35663585743649254502012-02-02T23:01:49.836+02:002012-02-02T23:01:49.836+02:00I agree with this and practice catch/throw; often ...I agree with this and practice catch/throw; often (specifically to keep the call stack intact). But I wonder about the "price" of it. Does bubbling the same exception up the chain without ever rethrowing it really incur a sigificant cost?<br />More importantly, ultimately at the end of all the try/catch/throw; blocks, not matter how nested they are, somebody eventually has to handle it (or an application crash will occur). When somebody DOES handle it, it most likely is going to result in some form of IO. Either writing a log to disk, or even halting any execution on the UI with a visible error message to alert the user.<br />Won't the price in time bubbling up the exception pale in comparison to the price of handling the exception with IO/UI? Is it even worth worrying about the minuscule amount of time taken to bubble up an exception when you know you will have to wait for the much longer IO operation, or worse yet a user error prompt?Hydroslidehttps://www.blogger.com/profile/17117175407223674202noreply@blogger.comtag:blogger.com,1999:blog-7988792589954261688.post-79896395932024288122012-02-02T18:48:25.862+02:002012-02-02T18:48:25.862+02:00In c# there is no difference between those two blo...In c# there is no difference between those two blocks. Is it different somehow in Java? Or did you mean to say...<br /><br />catch (Exception x) {<br /> throw new Exception(x);<br />}<br /><br />THAT is accomplishing nothing, but hurting performance, and as you say, you lose the stack trace unless the constructor for the new exception saves it, and then you're copying data, another unnecessary operation.Jasminehttps://www.blogger.com/profile/09618734526176282409noreply@blogger.comtag:blogger.com,1999:blog-7988792589954261688.post-32806565431878253352012-02-02T16:47:46.542+02:002012-02-02T16:47:46.542+02:00I agree for the most part...but please refer to Bi...I agree for the most part...but please refer to Bill wagner's excellent article "Working Effectively with Exceptions" for an explanation of what's wrong with catch(Exception) in the .NET environment:<br />http://visualstudiomagazine.com/Articles/2009/08/01/Working-Effectively-with-Exceptions.aspx?Page=3Clancyhttps://www.blogger.com/profile/12695730055125201803noreply@blogger.comtag:blogger.com,1999:blog-7988792589954261688.post-71979981392089122482012-02-02T16:26:47.064+02:002012-02-02T16:26:47.064+02:00This is another viewpoint, which may be true for m...This is another viewpoint, which may be true for most scenarios. But anyway I can't generalize that "exceptions can not include warning, debug & info level logging".CBhttps://www.blogger.com/profile/13504212299235753253noreply@blogger.comtag:blogger.com,1999:blog-7988792589954261688.post-53600143457629173942012-02-02T16:21:27.988+02:002012-02-02T16:21:27.988+02:00This is true. "Adding to message part" i...This is true. "Adding to message part" is a general statement.CBhttps://www.blogger.com/profile/13504212299235753253noreply@blogger.comtag:blogger.com,1999:blog-7988792589954261688.post-15339177531708938602012-02-02T15:56:09.322+02:002012-02-02T15:56:09.322+02:00I'm surprised that #7 has garnered no negativi...I'm surprised that #7 has garnered no negativity. The major problem (in Java code) are beginner programmers that create extensive Exception class hierarchies for their code that make maintenance and integration a nightmare. ex, FileException, FileOpenException, FileOpenNonExclusiveWriteException instead of using the built in IOException with a meaningful message since it matters little whether how the exception occurred for most other than an IOException occurred. Think about how the error conditions will be handled in the program, not how a programmer will debug it.<br /><br />Another is the eternal (in Java anyways) RuntimeException vs Exception hierarchy, and having to declare thrown exceptions. I personally feel that the designers of Java made a mistake here and should only have instituted RuntimeExceptions. Throw clauses on the methods would be indications of potential exceptional cases, which is all they are now really, except those that do not descend from RuntimeException must be declared in every method up the stack or caught, whether desired or not.Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-7988792589954261688.post-39979466339560669592012-02-02T14:03:38.776+02:002012-02-02T14:03:38.776+02:00I disagree with using exceptions for anything &quo...I disagree with using exceptions for anything "less or equal to" warning (point 8). Warnings, infos and debugs are cumulative (you can land up with multiple warnings per operation); Exceptions are not.<br /><br />Furthermore, an exception precludes a return value - and by definition (well, at least by mine) a warning should should return a value and indicate something may be crazy with it; even more-so with info and debug. You should be logging warnings, infos and debugs directly to your logging system and not relying on exceptions - and even in some cases rely on the return type to convey them (e.g. CompileResults from CodeDom).<br /><br />This mean that exceptions can be "Fatal Error" (which by definition should be left to bubble to your 'Main' and logged from there - in other words a fatal error is akin to an OS kernel panic) or simply "Error" (which would inform the user of the problem - or dealt with in some other fashion if possible).<br /><br />When in doubt figure out where the word Exception comes from: something exceptional (out of the ordinary) has happened. Info and debug are by a very large margin not exceptional - warning may be exceptional depending on the scenario at-hand.jcdickinsonhttps://www.blogger.com/profile/03059168484410900320noreply@blogger.comtag:blogger.com,1999:blog-7988792589954261688.post-20110668983665036252012-02-01T20:01:01.739+02:002012-02-01T20:01:01.739+02:00Thanks Alan for the important recall. These practi...Thanks Alan for the important recall. These practices are written as language independent.CBhttps://www.blogger.com/profile/13504212299235753253noreply@blogger.com