<p>In Java (or any other language with checked exceptions), when creating your own exception class, how do you decide whether it should be checked or unchecked?</p>

<p>My instinct is to say that a checked exception would be called for in cases where the caller might be able to recover in some productive way, where as an unchecked exception would be more for unrecoverable cases, but I'd be interested in other's thoughts.</p>

[{'answer_id': 27582, 'author': 'Espo', 'author_id': 2257, 'author_profile': 'https://Stackoverflow.com/users/2257', 'pm_score': 6, 'selected': False, 'text': '<p>From <a href="http://lankireddy.blogspot.com/2007/10/checked-vs-unchecked-exceptions.html" rel="noreferrer">A Java Learner</a>:</p>\n\n<blockquote>\n  <p>When an exception occurs, you have to\n  either catch and handle the exception,\n  or tell compiler that you can\'t handle\n  it by declaring that your method\n  throws that exception, then the code\n  that uses your method will have to\n  handle that exception (even it also\n  may choose to declare that it throws\n  the exception if it can\'t handle it). </p>\n  \n  <p>Compiler will check that we have done\n  one of the two things (catch, or\n  declare).  So these are called Checked\n  exceptions.   But Errors, and Runtime\n  Exceptions are not checked for by\n  compiler (even though you can choose\n  to catch, or declare, it is not\n  required).  So, these two are called\n  Unchecked exceptions.</p>\n  \n  <p>Errors are used to represent those\n  conditions which occur outside the\n  application, such as crash of the\n  system.  Runtime exceptions are\n  usually occur by fault in the\n  application logic.  You can\'t do\n  anything in these situations.  When\n  runtime exception occur, you have to\n  re-write your program code.  So, these\n  are not  checked by compiler.  These\n  runtime exceptions will uncover in\n  development, and testing period.  Then\n  we have to refactor our code to remove\n  these errors.</p>\n</blockquote>\n'}, {'answer_id': 27591, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': -1, 'selected': False, 'text': "<p>The rule I use is: never use unchecked exceptions! (or when you don't see any way around it)</p>\n\n<p>From the point of view of the developer using your library or the end-user using your library/application it really sucks to be confronted with an application that crashes due to an uncought exception. And counting on a catch-all is no good either.</p>\n\n<p>This way the end user can still be presented with an error message, instead of the application completely disappearing.</p>\n"}, {'answer_id': 27611, 'author': 'David Crow', 'author_id': 2783, 'author_profile': 'https://Stackoverflow.com/users/2783', 'pm_score': 1, 'selected': False, 'text': "<p>Checked exceptions are useful for recoverable cases where you want to provide information to the caller (i.e. insufficient permissions, file not found, etc).</p>\n\n<p>Unchecked exceptions are used rarely, if at all, for informing the user or programmer of serious errors or unexpected conditions during run-time. Don't throw them if you're writing code or libraries that will be used by others, as they may not be expecting your software to throw unchecked exceptions since the compiler doesn't force them to be caught or declared.</p>\n"}, {'answer_id': 27629, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 6, 'selected': False, 'text': '<blockquote>\n<p>The rule I use is: never use unchecked exceptions! (or when you don\'t see any way around it)</p>\n</blockquote>\n<p>There’s a case for the opposite: <em>never</em> use checked exceptions. I’m reluctant to take sides in the debate (there’s definitely good arguments on both sides!) but a fair number of experts feel that checked exceptions were a wrong decision in hindsight.</p>\n<p>For some discussion, check the WikiWikiWeb’s <a href="http://www.c2.com/cgi/wiki?CheckedExceptionsAreOfDubiousValue" rel="nofollow noreferrer">“Checked exceptions are of dubious value”</a>. Another example of an early, extensive argument is <a href="https://radio-weblogs.com/0122027/stories/2003/04/01/JavasCheckedExceptionsWereAMistake.html" rel="nofollow noreferrer">Rod Waldhoff’s blog post</a>.</p>\n'}, {'answer_id': 73355, 'author': 'VonC', 'author_id': 6309, 'author_profile': 'https://Stackoverflow.com/users/6309', 'pm_score': 5, 'selected': False, 'text': '<p>Here is my \'final rule of thumb\'.<br>\nI use:</p>\n\n<ul>\n<li><strong>unchecked exception</strong> within the code of my method for a <strong>failure due to the caller</strong> (that involves an <strong><a href="https://stackoverflow.com/questions/61604/api-documentation-and-value-limits-do-they-match">explicit and complete documentation</a></strong>)</li>\n<li><strong>checked exception</strong> for a <strong>failure due to the <a href="http://dictionary.reference.com/browse/callee" rel="noreferrer">callee</a></strong> that I need to make explicit to anyone wanting to use my code</li>\n</ul>\n\n<p>Compare to the previous answer, this is a clear rationale (upon which one can agree or disagree) for the use of one or the other (or both) kind of exceptions.</p>\n\n<hr>\n\n<p>For both of those exceptions, I will create my own unchecked and checked Exception for my application (a good practice, <a href="https://stackoverflow.com/questions/33497/how-do-i-recover-from-an-unchecked-exception#33564">as mentionned here</a>), except for very common unchecked exception (like NullPointerException)</p>\n\n<p>So for instance, the goal of this particular function below is to make (or get if already exist) an object,<br>\nmeaning:</p>\n\n<ul>\n<li>the container of the object to make/get MUST exist (responsibility of the CALLER<br>\n=> unchecked exception, AND clear javadoc comment for this called function)</li>\n<li>the other parameters can not be null<br>\n(choice of the coder to put that on the CALLER: the coder will not check for null parameter but the coder DOES DOCUMENT IT)</li>\n<li>the result CAN NOT BE NULL<br>\n(responsibility and choice of the code of the callee, choice which will be of great interest for the caller<br>\n=> checked exception because every callers MUST take a decision if the object can not be created/found, and that decision must be enforced at the compilation time: they can not use this function without having to deal with this possibility, meaning with this <em>checked</em> exception).  </li>\n</ul>\n\n<p>Example:</p>\n\n<hr>\n\n<pre><code>/**\n * Build a folder. &lt;br /&gt;\n * Folder located under a Parent Folder (either RootFolder or an existing Folder)\n * @param aFolderName name of folder\n * @param aPVob project vob containing folder (MUST NOT BE NULL)\n * @param aParent parent folder containing folder \n *        (MUST NOT BE NULL, MUST BE IN THE SAME PVOB than aPvob)\n * @param aComment comment for folder (MUST NOT BE NULL)\n * @return a new folder or an existing one\n * @throws CCException if any problems occurs during folder creation\n * @throws AssertionFailedException if aParent is not in the same PVob\n * @throws NullPointerException if aPVob or aParent or aComment is null\n */\nstatic public Folder makeOrGetFolder(final String aFoldername, final Folder aParent,\n    final IPVob aPVob, final Comment aComment) throws CCException {\n    Folder aFolderRes = null;\n    if (aPVob.equals(aParent.getPVob() == false) { \n       // UNCHECKED EXCEPTION because the caller failed to live up\n       // to the documented entry criteria for this function\n       Assert.isLegal(false, "parent Folder must be in the same PVob than " + aPVob); }\n\n    final String ctcmd = "mkfolder " + aComment.getCommentOption() + \n        " -in " + getPNameFromRepoObject(aParent) + " " + aPVob.getFullName(aFolderName);\n\n    final Status st = getCleartool().executeCmd(ctcmd);\n\n    if (st.status || StringUtils.strictContains(st.message,"already exists.")) {\n        aFolderRes = Folder.getFolder(aFolderName, aPVob);\n    }\n    else {\n        // CHECKED EXCEPTION because the callee failed to respect his contract\n        throw new CCException.Error("Unable to make/get folder \'" + aFolderName + "\'");\n    }\n    return aFolderRes;\n}\n</code></pre>\n'}, {'answer_id': 87779, 'author': 'Stephane', 'author_id': 13501, 'author_profile': 'https://Stackoverflow.com/users/13501', 'pm_score': 6, 'selected': False, 'text': '<p>On any large enough system, with many layers, checked exception are useless as, anyway, you need an architectural level strategy to handle how the exception will be handled (use a fault barrier)</p>\n\n<p>With checked exceptions your error handling stategy is micro-managed and its unbearable on any large system.</p>\n\n<p>Most of the time you don\'t know if an error is "recoverable" because you don\'t know in what layer the caller of your API is located.</p>\n\n<p>Let\'s say that I create a StringToInt API that converts the string representation of an integer to an Int. Must I throw a checked exception if the API is called with the "foo" string ? Is it recoverable ? I don\'t know because in his layer the caller of my StringToInt API may already have validated the input, and if this exception is thrown it\'s either a bug or a data corruption and it isn\'t recoverable for this layer.</p>\n\n<p>In this case the caller of the API does not want to catch the exception. He only wants to let the exception "bubble up". If I chose a checked exception, this caller will have plenty of useless catch block only to artificially rethrow the exception.</p>\n\n<p>What is recoverable depends most of the time on the caller of the API, not on the writter of the API. An API should not use checked exceptions as only unchecked exceptions allows to choose to either catch or ignore an exception.</p>\n'}, {'answer_id': 322801, 'author': 'Yoni', 'author_id': 36071, 'author_profile': 'https://Stackoverflow.com/users/36071', 'pm_score': 4, 'selected': False, 'text': "<p>It's not just a matter of the ability to recover from the exception. What matter most, in my opinion, is whether the caller is interested in catching the exception or not.</p>\n\n<p>If you write a library to be used elsewhere, or a lower-level layer in your application, ask yourself if the caller is interested in catching (knowing about) your exception. If he is not, then use an unchecked exception, so you don't burden him unnecessarily.</p>\n\n<p>This is the philosophy used by many frameworks. Spring and hibernate, in particularly, come to mind - they convert known checked exception to unchecked exception precisely because checked exceptions are overused in Java. One example that I can think of is the JSONException from json.org, which is a checked exception and is mostly annoying - it should be unchecked, but the developer simply haven't thought it through.</p>\n\n<p>By the way, most of the time the caller's interest in the exception is directly correlated to the ability to recover from the exception, but that is not always the case.</p>\n"}, {'answer_id': 322889, 'author': 'OscarRyz', 'author_id': 20654, 'author_profile': 'https://Stackoverflow.com/users/20654', 'pm_score': 5, 'selected': False, 'text': '<p>You\'re correct. </p>\n\n<p><strong>Unchecked exceptions</strong> are used to let the system <a href="http://en.wikipedia.org/wiki/Fail-fast" rel="noreferrer">fail fast</a> which is a good thing. You should clearly state what is your method expecting in order to work properly.  This way you can validate the input only once.</p>\n\n<p>For instance:</p>\n\n<pre><code>/**\n * @params operation - The operation to execute.\n * @throws IllegalArgumentException if the operation is "exit"\n */\n public final void execute( String operation ) {\n     if( "exit".equals(operation)){\n          throw new IllegalArgumentException("I told you not to...");\n     }\n     this.operation = operation; \n     .....  \n }\n private void secretCode(){\n      // we perform the operation.\n      // at this point the opreation was validated already.\n      // so we don\'t worry that operation is "exit"\n      .....  \n }\n</code></pre>\n\n<p>Just to put an example. The point is, if the system fails fast, then you\'ll know where and why it did fail.  You\'ll get an stacktrace like:</p>\n\n<pre><code> IllegalArgumentException: I told you not to use "exit" \n at some.package.AClass.execute(Aclass.java:5)\n at otherPackage.Otherlass.delegateTheWork(OtherClass.java:4569)\n ar ......\n</code></pre>\n\n<p>And you\'ll know what happened. The OtherClass in the "delegateTheWork" method ( at line 4569 ) called your class with the "exit" value, even when it shouldn\'t  etc.</p>\n\n<p>Otherwise you would have to sprinkle validations all over your code and that\'s error prone. Plus, sometimes it is hard to track what went wrong and you may expect hours of frustrating  debugging </p>\n\n<p>Same thing happens with NullPointerExceptions. If you have a 700 lines class with some 15 methods, that uses 30 attributes and none of them can be null, instead of validating in each of those methods for nullability you could make all those attributes read-only and validate them in the constructor or factory method.</p>\n\n<pre><code> public static MyClass createInstane( Object data1, Object data2 /* etc */ ){ \n      if( data1 == null ){ throw NullPointerException( "data1 cannot be null"); }\n\n  }\n\n\n  // the rest of the methods don\'t validate data1 anymore.\n  public void method1(){ // don\'t worry, nothing is null \n      ....\n  }\n  public void method2(){ // don\'t worry, nothing is null \n      ....\n  }\n  public void method3(){ // don\'t worry, nothing is null \n      ....\n  }\n</code></pre>\n\n<p><strong>Checked exceptions</strong> Are useful when the programmer ( you or your co-workers ) did everything right, validated the input, ran tests, and all the code is perfect, but the code connects to a third party webservice that may be down ( or a file you were using  was deleted by another external process etc ) . The webservice may even be validate before the connection is attempted, but during the data transfer something went wrong.</p>\n\n<p>In that scenario there is nothing that you or your co-workers can do to help it. But still you have to do something and not let the application just die and disappear in the eyes of the user.  You use a checked exception for that and handle the exception, what can you do when that happens?, most of the time , just to attempt to log the error, probably save your work ( the app work ) and present a message to the user. ( The site blabla is down, please retry later etc. ) </p>\n\n<p>If the checked exception are overused ( by  adding the "throw Exception" in the all the methods signatures ) , then your code will become very fragile, because everyone will ignore that exception ( because is too general ) and the quality of code will be seriously compromised.</p>\n\n<p>If you overuse unchecked exception something similar will happen. The users of that code don\'t know if something may go wrong an a lot of try{...}catch( Throwable t ) will appear.</p>\n'}, {'answer_id': 6662165, 'author': 'Colin Saxton', 'author_id': 840421, 'author_profile': 'https://Stackoverflow.com/users/840421', 'pm_score': 3, 'selected': False, 'text': "<p>You can call it a checked or unchecked exception; however, <em>both</em> types of exception can be caught by the programmer, so the best answer is: write <em>all</em> of your exceptions as <em>unchecked</em> and document them. That way the developer who uses your API can choose whether he or she wants to catch that exception and do something. Checked exceptions are a complete waste of everyone's time and it makes your code a shocking nightmare to look at. Proper unit testing will then bring up any exceptions that you may have to catch and do something with.</p>\n"}, {'answer_id': 13944065, 'author': 'Reachgoals', 'author_id': 1874487, 'author_profile': 'https://Stackoverflow.com/users/1874487', 'pm_score': 3, 'selected': False, 'text': '<p><strong>Checked Exception:</strong>\n   If client can recover from an exception and would like to continue, use checked exception.</p>\n\n<p><strong>Unchecked Exception:</strong>\n   If a client can\'t do any thing after the exception, then raise unchecked exception.</p>\n\n<p>Example: If you are expected to do arithmetic operation in a method A() and based on the output from A(), you have to another operation. If the output is null from method A() which you are not expecting during the run time, then you are expected to throw Null pointer Exception which is Run time exception. </p>\n\n<p>Refer <a href="http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html">here</a></p>\n'}, {'answer_id': 15602506, 'author': 'Scott Kurz', 'author_id': 1499766, 'author_profile': 'https://Stackoverflow.com/users/1499766', 'pm_score': 2, 'selected': False, 'text': '<p>I agree with the preference for unchecked exceptions as a rule, especially when designing an API.   The caller can always choose to catch a documented, unchecked exception.  You\'re just not needlessly forcing the caller to.</p>\n\n<p>I find checked exceptions useful at the lower-level, as implementation detail.   It often seems like a better flow of control mechanism than having to manage a specified error "return code".  It can sometimes help see the impact of an idea for a low level code change too... declare a checked exception downstream and see who would need to adjust.   This last point doesn\'t apply if there are a lot of generic:   <strong>catch(Exception e)</strong>  or <strong>throws Exception</strong>  which is usually not too well-thought out anyway.</p>\n'}, {'answer_id': 19061110, 'author': 'Gili', 'author_id': 14731, 'author_profile': 'https://Stackoverflow.com/users/14731', 'pm_score': 9, 'selected': True, 'text': "<p>Checked Exceptions are great, so long as you understand when they should be used. The Java core API fails to follow these rules for SQLException (and sometimes for IOException) which is why they are so terrible.</p>\n\n<p><strong>Checked Exceptions</strong> should be used for <strong>predictable</strong>, but <strong>unpreventable</strong> errors that are <strong>reasonable to recover from</strong>.</p>\n\n<p><strong>Unchecked Exceptions</strong> should be used for everything else.</p>\n\n<p>I'll break this down for you, because most people misunderstand what this means.</p>\n\n<ol>\n<li><strong>Predictable but unpreventable</strong>: The caller did everything within their power to validate the input parameters, but some condition outside their control has caused the operation to fail. For example, you try reading a file but someone deletes it between the time you check if it exists and the time the read operation begins. By declaring a checked exception, you are telling the caller to anticipate this failure.</li>\n<li><strong>Reasonable to recover from</strong>: There is no point telling callers to anticipate exceptions that they cannot recover from. If a user attempts to read from an non-existing file, the caller can prompt them for a new filename. On the other hand, if the method fails due to a programming bug (invalid method arguments or buggy method implementation) there is nothing the application can do to fix the problem in mid-execution. The best it can do is log the problem and wait for the developer to fix it at a later time.</li>\n</ol>\n\n<p>Unless the exception you are throwing meets <strong>all</strong> of the above conditions it should use an Unchecked Exception.</p>\n\n<p><strong>Reevaluate at every level</strong>: Sometimes the method catching the checked exception isn't the right place to handle the error. In that case, consider what is reasonable for your own callers. If the exception is predictable, unpreventable and reasonable for them to recover from then you should throw a checked exception yourself. If not, you should wrap the exception in an unchecked exception. If you follow this rule you will find yourself converting checked exceptions to unchecked exceptions and vice versa depending on what layer you are in.</p>\n\n<p>For both checked and unchecked exceptions, <strong>use the right abstraction level</strong>. For example, a code repository with two different implementations (database and filesystem) should avoid exposing implementation-specific details by throwing <code>SQLException</code> or <code>IOException</code>. Instead, it should wrap the exception in an abstraction that spans all implementations (e.g. <code>RepositoryException</code>).</p>\n"}, {'answer_id': 21598741, 'author': 'ramu p', 'author_id': 3278858, 'author_profile': 'https://Stackoverflow.com/users/3278858', 'pm_score': 1, 'selected': False, 'text': "<p>Whnever an exception is less likely expected, and we can proceed even after catching that, and we can not do anything to avoid that exception then we can use checked exception.</p>\n\n<p>Whenever we want to do something meaningful when a particular exceptions happens and when that exception is expected but not certain, then we can use checked exception.</p>\n\n<p>Whenever exception navigating in different layers, we don't need to catch it in every layer, in that case, we can use runtime exception or wrap exception as unchecked exception.</p>\n\n<p>Runtime exception is used when exception most likely to be happened, there is no way of going further and nothing can be recoverable. So in this case we can take precautions with respect to that exception. EX: NUllPointerException, ArrayOutofBoundsException. These are more likely to happen. In this scenario, we can take precautions while coding to avoid such exception. Otherwise we will have to write try catch blocks every where.</p>\n\n<p>More general exceptions can be made Unchecked, less general are checked.</p>\n"}, {'answer_id': 23439719, 'author': 'user3598189', 'author_id': 3598189, 'author_profile': 'https://Stackoverflow.com/users/3598189', 'pm_score': 4, 'selected': False, 'text': '<p>Here is a very simple solution to your Checked/Unchecked dilemma.</p>\n\n<p>Rule 1: Think of a Unchecked Exception as a testable condition before code executes.\nfor example…</p>\n\n<pre><code>x.doSomething(); // the code throws a NullPointerException\n</code></pre>\n\n<p>where x is null...\n…the code should possibly have the following…</p>\n\n<pre><code>if (x==null)\n{\n    //do something below to make sure when x.doSomething() is executed, it won’t throw a NullPointerException.\n    x = new X();\n}\nx.doSomething();\n</code></pre>\n\n<p>Rule 2: Think of a Checked Exception as an un-testable condition that may occur while the code executes.</p>\n\n<pre><code>Socket s = new Socket(“google.com”, 80);\nInputStream in = s.getInputStream();\nOutputStream out = s.getOutputStream();\n</code></pre>\n\n<p>…in the example above, the URL (google.com) may be unavailable to due the DNS server being down. Even at the instant the DNS server was working and resolved the ‘google.com’ name to an IP address, if the connection is made to google.com, at anytime afterword, the network could go down. You simply can not test the network all the time before reading and writing to streams.</p>\n\n<p>There are times where the code simply must execute before we can know if there is a problem. By forcing developers to write their code in such a way to force them to handle these situations via Checked Exception, I have to tip my hat to the creator of Java that invented this concept.</p>\n\n<p>In general, almost all the APIs in Java follow the 2 rules above. If you try to write to a file, the disk could fill up before completing the write. It is possible that other processes had caused the disk to become full. There is simply no way to test for this situation. For those who interact with hardware where at any time, using the hardware can fail, Checked Exceptions seem to be an elegant solution to this problem.</p>\n\n<p>There is a gray area to this. In the event that many tests are needed (a mind blowing if statement with lots of &amp;&amp; and ||), the exception thrown will be a CheckedException simply because it’s too much of a pain to get right — you simply can’t say this problem is a programming error. If there are much less than 10 tests (e.g. ‘if (x == null)’), then the programmer error should be a UncheckedException.</p>\n\n<p>Things get interesting when dealing with language interpreters. According to the rules above, should a Syntax Error be considered a Checked or Unchecked Exception? I would argue that if the syntax of the language can be tested before it gets executed, it should be an UncheckedException. If the language can not be tested — similar to how assembly code runs on a personal computer, then the Syntax Error should be a Checked Exception.</p>\n\n<p>The 2 rules above will probably remove 90% of your concern over which to choose from. To summarize the rules, follow this pattern…\n1) if the code to be execute can be tested before it’s executed for it to run correctly and if an Exception occurs — a.k.a. a programmer error, the Exception should be an UncheckedException (a subclass of RuntimeException).\n2) if the code to be executed can not be tested before it’s executed for it to run correctly, the Exception should be a Checked Exception (a subclass of Exception).</p>\n'}, {'answer_id': 33167087, 'author': 'Jacky', 'author_id': 1318528, 'author_profile': 'https://Stackoverflow.com/users/1318528', 'pm_score': 1, 'selected': False, 'text': '<p>I think we can think about exeptions from several questions:</p>\n\n<p><strong>why does exeption happen? What can we do when it happens</strong> </p>\n\n<p><strong>by mistake, a bug.</strong> such as a method of null object is called. </p>\n\n<pre><code>String name = null;\n... // some logics\nSystem.out.print(name.length()); // name is still null here\n</code></pre>\n\n<p>This kind of exception should be fixed during test. Otherwise, it breaks the production, and you got a very high bug which needs to be fixed immediately. This kind of exceptions do not need be checked. </p>\n\n<p><strong>by input from external,</strong> you cannot control or trust the output of external service.</p>\n\n<pre><code>String name = ExternalService.getName(); // return null\nSystem.out.print(name.length());    // name is null here\n</code></pre>\n\n<p>Here, you may need to check whether the name is null if you want to continue when it is null, otherwise, you can let it alone and it will stop here and give the caller the runtime exception. \nThis kind of exceptions do not need be checked.</p>\n\n<p><strong>by runtime exception from external,</strong> you cannot control or trust the external service.</p>\n\n<p>Here, you may need to catch all exceptions from ExternalService if you want to continue when it happens, otherwise, you can let it alone and it will  stop here and give the caller the runtime exception. </p>\n\n<p><strong>by checked exception from external,</strong> you cannot control or trust the external service.</p>\n\n<p>Here, you may need to catch all exceptions from ExternalService if you want to continue when it happens, otherwise, you can let it alone and it will  stop here and give the caller the runtime exception. </p>\n\n<p><strong>In this case, do we need to know what kind of exception happened in ExternalService?</strong> It depends:</p>\n\n<ol>\n<li><p>if you can handle some kinds of exceptions, you need to catch them and process. For others, bubble them.</p></li>\n<li><p>if you need log or response to user the specific execption, you can catch them. For others, bubble them.</p></li>\n</ol>\n'}, {'answer_id': 43873791, 'author': 'Akash Aggarwal', 'author_id': 5800902, 'author_profile': 'https://Stackoverflow.com/users/5800902', 'pm_score': 0, 'selected': False, 'text': '<p>I think when declaring Application Exception it should be Unchecked Exception i.e., subclass of RuntimeException.\nThe reason is it will not clutter application code with try-catch and throws declaration on method. If your application is using Java Api which throws checked exceptions that anyways need to be handle. For other cases, the application can throw unchecked exception. If the application caller still needs to handle unchecked exception, it can be done. </p>\n'}, {'answer_id': 44850154, 'author': 'Denys', 'author_id': 3784768, 'author_profile': 'https://Stackoverflow.com/users/3784768', 'pm_score': 2, 'selected': False, 'text': '<p>Here is I want to share my opinion I have after many years of development experience:</p>\n\n<ol>\n<li><p>Checked exception. This is a part of business use case or call flow, this is a part of application logic we expect or not expect. For example connection rejected, condition is not satisfied etc. We need to handle it and show corresponding message to user with instructions what happened and what to do next (try again later etc).\nI usually call it post-processing exception or "user" exception.</p></li>\n<li><p>Unchecked exception. This is a part of programming exception, some mistake in software code programming (bug, defect) and reflects a way how programmers must use API as per documentation. If an external lib/framework doc says it expects to get data in some range and non null, because NPE or IllegalArgumentException will be thrown, programmer should expect it and use API correctly as per documentation. Otherwise the exception will be thrown.\nI usually call it pre-processing exception or "validation" exception.</p></li>\n</ol>\n\n<p>By target audience. Now let\'s talk about target audience or group of people the exceptions have been designed (as per my opinion):</p>\n\n<ol>\n<li>Checked exception. Target audience is users/clients.</li>\n<li>Unchecked exception. Target audience is developers. By other words unchecked exception are designed for developers only.</li>\n</ol>\n\n<p>By application development lifecycle phase.</p>\n\n<ol>\n<li>Checked exception is designed to exist during whole production lifecycle as normal and expected mechanism an application handles exceptional cases.</li>\n<li>Unchecked exception is designed to exist only during application development/testing lifecycle, all of them should be fixed during that time and should not be thrown when an application is running on production already.</li>\n</ol>\n\n<p>The reason why frameworks usually use unchecked exceptions (Spring for example) is that framework cannot determine the business logic of your application, this is up to developers to catch then and design own logic.</p>\n'}, {'answer_id': 51556224, 'author': 'ailhanli', 'author_id': 1300198, 'author_profile': 'https://Stackoverflow.com/users/1300198', 'pm_score': 2, 'selected': False, 'text': "<p>We have to distinguish these two types of exception based on whether it is programmer error or  not. </p>\n\n<ul>\n<li><strong><em>If an error is a programmer error, it must be an Unchecked Exception</em>.</strong>  For example:\nSQLException/IOException/NullPointerException. These exceptions are\nprogramming errors. They should be handled by programmer. While in\nJDBC API, SQLException is Checked Exception, In Spring JDBCTemplate\nit is an Unchecked Exception.Programmer doesn't worry about\nSqlException, when use Spring.</li>\n<li><strong><em>If an error is not a programmer error and the reason is coming from external, it must be a Checked Exception.</em></strong> For example: if the\nfile is deleted or file permission is changed by someone else, It\nshould be recovered.</li>\n</ul>\n\n<p>FileNotFoundException is good example to understand subtle differences. FileNotFoundException is thrown in case file is not found. There are two reason for this exception. If the file path is defined by developer or taking from end user via GUI it should be an Unchecked Exception. If the file is deleted by someone else, it should be a Checked Exception.</p>\n\n<p>Checked Exception can be handled in two ways. These are using try-catch or propagate the exception. In  case of propagation of exception, all methods in call stack will be <strong>tightly coupled</strong> because of exception handling. That's why, we have to use Checked Exception carefully.</p>\n\n<p>In case you develop an layered enterprise system, you have to choose mostly unchecked exception to throw, but don't forget to use checked exception for the case you cannot do anything.</p>\n"}]
['https://Stackoverflow.com/questions/27578', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/797/']