I read some code of a colleague and found that he often catches various exceptions and then always throws a 'RuntimeException' instead. I always thought this is very bad practice. Am I wrong?
-
25__"The price of checked exceptions is an Open/Closed Principle violation. If you throw a checked exception from a method in your code and the catch is three levels above, you must declare that exception in the signature of each method between you and the catch. This means that a change at a low level of the software can force signature changes on many higher levels."__ —Robert C. Martin, «Clean Code», page 107 – Songo Nov 09 '14 at 11:10
-
9It's interesting to note that Jim Waldo rants against unchecked exceptions in "Java: The Good Parts" http://shop.oreilly.com/product/9780596803742.do saying that adult programmers should only throw checked exceptions. We read it in our JUG only 6 years ago when it came out and it seemed like good advice! Now, with functional programming, checked exceptions are completely unwieldy. Languages like Scala and Kotlin don't even have them. I've started wrapping checked in unchecked exceptions too. – GlenPeterson Jun 28 '16 at 13:57
-
1@GlenPeterson you also have the advice in FP to avoid execetions altogether and use sum types instead – jk. Mar 27 '18 at 12:35
-
There’s also the obvious case of functional interfaces: the builtin functional interfaces (i.e. `Function`, `Predicate`, etc) do not have parametrized throws clauses. This means that you *need* to catch, wrap, and rethrow any checked exceptions in the inner loop of any stream() methods. That in and of itself tips the balance for me on whether checked exceptions are a bad idea. – Joel Cornett Mar 27 '18 at 14:06
-
There’s nothing wrong with creating custom subclasses of RuntimeException in order to communicate meaning through your exception. – Joel Cornett Mar 27 '18 at 14:07
-
@jk. Great point. That's why I made these Union Types for Java: https://glenkpeterson.github.io/Paguro/apidocs/index.html?org/organicdesign/fp/oneOf/package-summary.html Maybe a little cumbersome because you have to make a brief subclass of the union type, but they work and I've been using them in production code for years. – GlenPeterson Mar 28 '18 at 13:07
-
1@Songo that isn't particularly true, you can wrap an underlying implementation's exceptions with your own layer's exceptions, and propagate these. – Ben Barkay Jun 24 '18 at 08:01
-
12019 Answer: Your college was 100% right in doing it. – earizon Jul 23 '19 at 10:54
13 Answers
I do not know enough context to know whether your colleague is doing something incorrectly or not, so I am going to argue about this in a general sense.
I do not think it is always an incorrect practice to turn checked exceptions into some flavor of runtime exception. Checked exceptions are often misused and abused by developers.
It is very easy to use checked exceptions when they are not meant to be used (unrecoverable conditions, or even control flow). Especially if a checked exception is used for conditions from which the caller cannot recover, I think it is justified to turn that exception to a runtime exception with a helpful message/state. Unfortunately in many cases when one is faced with an unrecoverable condition, they tend to have an empty catch block which is one of the worst things you can do. Debugging such an issue is one of the biggest pains a developer can encounter.
So if you think that you are dealing with a recoverable condition, it should be handled accordingly and the exception should not be turned into a runtime exception. If a checked exception is used for unrecoverable conditions, turning it into a runtime exception is justified.

- 8,250
- 4
- 35
- 53
-
20In most real-life applications, there are very few unrecoverable conditions. There's nearly alwas some level at which you can and should say "OK, this action failed, so we show/log a nice error message and continue with / wait for the next one". – Michael Borgwardt Nov 24 '11 at 13:31
-
9That's true, @MichaelBorgwardt, but the place for that sort of handling is often at the very highest level of the application, so whenever I see developers "handling" exceptions at lower levels, it's usually easy to remove their handling and just percolate the exception upwards. For example, a web framework like JSF catches exceptions at the highest level, prints log messages, and continues processing other requests (not saying the default handling is suitable, just an example). – DavidS Sep 11 '15 at 21:20
-
Anyone who writes an empty catch block should be fired on the spot, and confined to janitorial duties in a dungeon somewhere – Sarsaparilla May 16 '20 at 18:51
It can be GOOD. Please read this onjava.com article:
Most of the time, client code cannot do anything about SQLExceptions. Do not hesitate to convert them into unchecked exceptions. Consider the following piece of code:
public void dataAccessCode(){
try{
..some code that throws SQLException
}catch(SQLException ex){
ex.printStacktrace();
}
}
This catch block just suppresses the exception and does nothing. The justification is that there is nothing my client could do about an SQLException. How about dealing with it in the following manner?
public void dataAccessCode(){
try{
..some code that throws SQLException
}catch(SQLException ex){
throw new RuntimeException(ex);
}
}
This converts SQLException to RuntimeException. If SQLException occurs, the catch clause throws a new RuntimeException. The execution thread is suspended and the exception gets reported. However, I am not corrupting my business object layer with unnecessary exception handling, especially since it cannot do anything about an SQLException. If my catch needs the root exception cause, I can make use of the getCause() method available in all exception classes as of JDK1.4.
Throwing checked exceptions and not being able to recover from it is not helping.
Some people even think that checked exceptions should not be used at all. See http://www.ibm.com/developerworks/java/library/j-jtp05254/index.html
Recently, several well-regarded experts, including Bruce Eckel and Rod Johnson, have publicly stated that while they initially agreed completely with the orthodox position on checked exceptions, they've concluded that exclusive use of checked exceptions is not as good an idea as it appeared at first, and that checked exceptions have become a significant source of problems for many large projects. Eckel takes a more extreme view, suggesting that all exceptions should be unchecked; Johnson's view is more conservative, but still suggests that the orthodox preference for checked exceptions is excessive. (It's worth noting that the architects of C#, who almost certainly had plenty of experience using Java technology, chose to omit checked exceptions from the language design, making all exceptions unchecked exceptions. They did, however, leave room for an implementation of checked exceptions at a later time.)
Also from the same link:
The decision to use unchecked exceptions is a complicated one, and it's clear that there's no obvious answer. The Sun advice is to use them for nothing, the C# approach (which Eckel and others agree with) is to use them for everything. Others say, "there's a middle ground."

- 3,137
- 6
- 25
- 33

- 561
- 3
- 3
No, you are not wrong. His practice is extremely misguided. You should throw an exception that captures the issue that caused it. RunTimeException is broad and over reaching. It should be a NullPointerException, ArgumentException, etc. Whatever accurately describes what went wrong. This provides the ability to differentiate issues that you should handle and let the program survive versus errors that should be a "Do not pass go" scenario. What he is doing is only slightly better than "On Error Resume Next" unless there is something missing in the info provided in the question.

- 1,497
- 17
- 21
-
However, for some APIs it makes sense to throw a generic exception that the caller can deal with, often you see an
Exception pattern bein guseed here. Indeed the RuntimeException is generally a poor choice. Also see Precise Rethrow under Java 7 – Martijn Verburg Nov 23 '11 at 16:50 -
1Thanks for the hint. And what if he throws a custom exception that he has implemented that inherits directly from RuntimeException? – RoflcoptrException Nov 23 '11 at 16:58
-
@Martjin I agree. To be fair though the circumstances it doesn't sound like the use is appropriate. I generally would avoid catching a host of exceptions and throwing a single one in all of their cases. Perhaps throwing the same up, wrapping it with additional info and throwing, or simply handling it. Programming doesn't have many absolutes so if I sounded dogmatic...I was ;) – Rig Nov 23 '11 at 17:33
-
@Roflcoptr The problem with catching a checked exception and throwing an unchecked exception (as apposed to a checked
Exception) is that unchecked exceptions are not designed to be caught/handled and should be used sparingly, not as a matter of habit. See [Unchecked Exceptions - The Controversy](http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html). – Gyan aka Gary Buyn Nov 23 '11 at 19:53 -
31@Gary Buyn: many people think that checked exception are a failed language design experiment and *they* are the ones that should be used sparingly, not as a matter of habit. – Michael Borgwardt Nov 23 '11 at 20:17
-
-
8@Gary Buyn: Here's an article that outlines the debate pretty well: http://www.ibm.com/developerworks/java/library/j-jtp05254/index.html Note also that over 15 years after Java introduced this feature, no other language has adopted it, and C++ has deprecated a similar feature. – Michael Borgwardt Nov 23 '11 at 20:56
-
@GaryBuyn: Josh Block expands on this issue in Effective Java, one of the best books on Java IMHO. An entire chapter is dedicated to correct use of checked and unchecked exceptions. One of the biggest things I would disagree is the the sparing use of unchecked exceptions. Every time you think your program goes into a bad state that it cannot recover from, you should throw some kind of runtime exception to make sure it is easier to find the bug later. – c_maker Nov 23 '11 at 22:01
-
7@c_maker: Actually, Bloch mostly promotes the orthodox view, and your comment seems to be mainly about using more exceptions, period. My view is that the only valid reason to use a checked exception is for a condition that you expect all callers to handle immediately. – Michael Borgwardt Nov 24 '11 at 13:26
-
1this answer should be -11 not +11 it is so far off base of best practices it is silly ... – Jan 09 '12 at 21:57
-
1Prove it. I have never ever seen any guidelines that say catch an exception and throw some generic exception with no meaning. You can wrap an exception and propagate something meaningful but the OP didn't say that is what is happening. He says he is just tossing a random runtime exception which will make it a living hell for someone to debug down the road. – Rig Jan 09 '12 at 22:58
-
16Unnecessary throwing checked exceptions violates encapsulation. What do you do, if a simple method like 'getAccounts()' throws you an 'SQLException', 'NullPointerException' or 'FileNotFoundException'? Can you handle it? Youll probably just 'catch(Exception e){}' it. Besides, those exceptions - its implementation specific! It should not be a part of the contract! All you need to know is that **there was an error**. And what if the implementation changes? Suddenly everything has to change, cause the method no longer throws 'SQLException', but an 'ParseXMLException' instead! – K.L. Nov 15 '12 at 15:32
-
http://onjava.com/pub/a/onjava/2003/11/19/exceptions.html?page=1 - here's a link to an interesting article on this topic. If I had the rep, id downvote this answer :( **edit** aaah, i see one of the later answers uses the same article as I do. +1 to that! – K.L. Nov 15 '12 at 15:35
-
@K.L. I strongly disagree with your point. Why should knowing the possible types of errors **not** be part of the contract? It allows you to take actions according to what went wrong, the same way you take actions according to the value of a returned object! If you simply put a `catch(Exception e){}`, you are either not coding your error handling properly or the `@throws` Javadoc is broken or incomplete. Also, changing the type of exception that is thrown is an incredibly **bad idea** from a backwards compatibility point of view! – Alexis Leclerc Oct 24 '14 at 15:58
-
1@AlexisLeclerc the point made by the article seems to be the opposite of what you have read from it. Changing thrown checked exception into other chcecked/unchecked exceptions before throwing further is good for backwards compatibility and encapsulation. If I force my client code to handle a File not found exception, then once I change my implementation to use an SQL database, I'm gonna force the client code to change. It would be much better if I caught the File/SQL exceptions and just throw a DataStorageException. – K.L. Oct 24 '14 at 18:22
-
1Adding detail to the exception makes sense only if that information can be used to fix the problem. If the client code cannot fix my problem (it's got nothing to do with my inner SQL queries/File reads, it just wants an AccountList!) I shouldn't even force it to handle them with a contract. They will just handle it as any other RuntimeException, without the need of rethrowing it all the way up. – K.L. Oct 24 '14 at 18:25
-
@K.L. I've just badly typed my last sentence. By `changing the type of exception that is thrown is an incredibly bad idea from a backwards compatibility point of view!`, I meant that if you have a widely used library (for example) and decide to change the type of exception thrown by some method, then most probably this method will cause code to break for this library's users. – Alexis Leclerc Oct 24 '14 at 18:47
-
@K.L. I agree with you that throwing too specific exceptions is not a good idea, since it might mean that the appropriate checks are not properly done _inside_ the method. But you have to be realistic too; you can't throw `Exception` everywhere (even though you _can_), you have to output a minimum of information about the possible errors. – Alexis Leclerc Oct 24 '14 at 18:47
-
@K.L. I think we're on the same page and that I've just misinterpreted your comment. I've understood it in the first place as an encouragement to always throw `Exception`. – Alexis Leclerc Oct 24 '14 at 19:03
-
1@K.L. I think that point is pretty rubbish. You normally wouldn't implement checked exceptions like that. You instead would have getAccounts() throw a AccountAccessiblityException, that wraps one of those specific exceptions. In that case, the api users has to the handle the unavoidable scenario that the accounts may not be fetchable. It doesn't have to be recoverable from programatically, the application can respond by displaying to the user that the specified data source is not accessible due to AccountsAccessibilityException::getMessage(). Opposed to crashing with a stack trace. – Jeremy Jan 09 '15 at 05:33
-
1@Jeremy how exactly is wrapping this beneficial? In one instance you throw RuntimeException("Could not access account data") in the other you throw AccountAccessiblityException. Both of them will need to propagate up until they get to a place that can handle that failure, (and with an IO fail it's not probable), or to a place that can display a message to the user. The reason to create custom exceptions is to create a data structure in them that provides additional data so that the code can recover/identify the reason for the fail. In this case no such information is needed. – K.L. Jan 14 '15 at 08:49
-
The difference however is that with an unchecked exception you dont need to put throws and catches for that specific type of exception all around your code just to propagate the exception up. So, to reiterate. If you can do something about a fail but need additional data, throw a proper custom exception with additional data, but dont leak implementation by throwing source errors, like File not found or bad sql query. If the code cant do anything to fix or recover from the issue, just throw a runtime exception that will go up to the point it will be displayed to the user. – K.L. Jan 14 '15 at 08:55
-
I don't think you are appreciating the difference between checked and unchecked exceptions. While I am sure you know, I will reiterate... a checked exception is one that is _unavoidable_ (Trying to connect to a webserver...) An unchecked exception is one that is avoidable (using a null reference, accessing an array with an index out of bounds.) Having an interface communicate that it may fail, and the programmer must appreciate that is not pointless... You don't want to tell a user that an array was indexed out of bounds, but you do want to tell them a webserver is inaccessible. – Jeremy Jan 15 '15 at 01:51
-
Discriminating between the two types of exceptions in such a way is very critical to building a solid framework/appplication. Programmers should be forced to handle errors that are not in their control, but should not be forced to handle errors they have made themselves. Just because there does not exist a structure in the exception to programatically resolve an error does not mean it should not exist... if all you do with exceptions is propagate them up to one huge try-catch then you are not using them properly. – Jeremy Jan 15 '15 at 01:54
-
So interfaces should throw exceptions appropriate to their level of abstraction. Even if that means simply wrapping an exception. If you have a login method, you might have it throw a LoginFailedException. The login method might use some account database that would throw AccountAccessibilityException that LoginFailedException would wrap. Till you eventually get to a point where you construct a message to the user, log the error & provide a default, The idea is that the application doesn't just crash... The caller always has control over how the errors are handled, and is forced to handle them. – Jeremy Jan 15 '15 at 02:05
It depends.
This practice may be even wise. There are many situations (for example in web developement), where if some exception happens, you are unable to do anything (because you cannot for example repair inconsistent DB from your code :-), only developer can do it). In these situations, it is wise to wrap the thrown exception into a runtime exception a rethrow it. Than you can catch all these exceptions in some exception handling layer, log the error and display the user some nice localized error code + message.
On the other hand, if the exception is not runtime (is checked), the developer of the API indicates, that this exception is resolvable and should be repaired. If its possible, than you should definitely do it.
The other solution might be to rethrow this checked exception into the calling layer, but if you were unable to solve it, where the exception occured, you will be likely unable to solve it here also...

- 279
- 1
- 6
-
You hope that the developer of the API knew what s/he was doing and used checked exceptions well. I started seeing APIs that favor throwing runtime exceptions while also documenting it so the client has the option to catch it if it wants to. – c_maker Nov 23 '11 at 22:31
-
A method which throws an exception cannot generally know if a caller might recover from it. On the other hand, I would suggest that a method should only let a checked exception thrown by an inner method to escape if knows why the inner method threw the exception, and the reason is consistent with the outer method's API. If an inner method throws a checked exception unexpectedly, letting it bubble up as a checked exception may leave the caller misinformed as to what happened. – supercat Jul 09 '14 at 20:10
-
2Thank you for mentioning the `exception handling layer` -- e.g. in a webapp, a filter. – Jake Toronto Oct 03 '14 at 17:11
TL;DR
Premise
- Runtime exceptions should be thrown when the error is irrecoverable: when the error is in the code, and does not depend on external state (thus, the recovery would be correcting the code).
- Checked exceptions should be thrown when the code is correct, but external state is not as expected: no network connectivity, file not found or is corrupt, etc.
Conclusion
We may rethrow a checked exception as a runtime exception if the propagating or interface code assumes that the underlying implementation depends on external state, when it clearly does not.
This section discusses the topic of when either of the exceptions should be thrown. You can skip to the next horizontal bar if you just want to read a more detailed explanation for the conclusion.
When is it appropriate to throw a runtime exception? You throw a runtime exception when it is clear that the code is incorrect, and that recovery is appropriate by modifying the code.
For instance, it is appropriate to throw a runtime exception for the following:
float nan = 1/0;
This will throw a division by zero runtime exception. This is appropriate because the code is defective.
Or for instance, here's a portion of HashMap
's constructor:
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
// more irrelevant code...
}
In order to fix the initial capacity or load factor, it is appropriate that you edit the code to ensure that the correct values are being passed in. It is not dependent on some far away server being up, on the current state of the disk, a file, or another program. That constructor being called with invalid arguments depends on the correctness of the calling code, be it a wrong calculation that led to the invalid parameters or inappropriate flow that missed an error.
When is it appropriate to throw a checked exception? You throw a checked exception when the issue is recoverable without changing the code. Or to put it in different terms, you throw a checked exception when the error is related to state while the code is correct.
Now the word "recover" may be tricky here. It could mean that you find another way to achieve the goal: For instance, if the server doesn't respond then you should try the next server. If that sort of recovery is possible for your case then that's great, but that's not the only thing recovery means -- recovery could simply be displaying an error dialog to the user that explains what happened, or if that's a server application then it could be sending an email to the administrator, or even merely logging the error appropriately and concisely.
Let's take the example that was mentioned in mrmuggles' answer:
public void dataAccessCode(){
try{
..some code that throws SQLException
}catch(SQLException ex){
throw new RuntimeException(ex);
}
}
This is not the correct way to handle the checked exception. The mere incapacity to handle the exception in this method's scope does not mean that the app should be crashed. Instead, it is appropriate to propagate it to a higher scope like so:
public Data dataAccessCode() throws SQLException {
// some code that communicates with the database
}
Which allows for the possibility of recovery by the caller:
public void loadDataAndShowUi() {
try {
Data data = dataAccessCode();
showUiForData(data);
} catch(SQLException e) {
// Recover by showing an error alert dialog
showCantLoadDataErrorDialog();
}
}
Checked exceptions are a static-analysis tool, they make it clear for a programmer what could go wrong in a certain call without requiring them to learn the implementation or going through a trial and error process. This makes it easy to ensure that no portions of the error flow will be ignored. Rethrowing a checked exception as a runtime exception is working against this labor-saving static analysis feature.
It is also worth mentioning that the calling layer has a better context of the grander scheme of things as has been demonstrated above. There could be many causes for that dataAccessCode
would be called, the specific reason for the call is only visible to the caller -- thus it is able to make a better decision at the correct recovery upon failure.
Now that we've got this distinction clear, we may proceed to deduce when it's ok to rethrow a checked exception as a runtime exception.
Given the above, when is it appropriate to rethrow a checked exception as a RuntimeException? When the code you are using assumes dependency on external state, but you can clearly assert that it does not depend on external state.
Consider the following:
StringReader sr = new StringReader("{\"test\":\"test\"}");
try {
doesSomethingWithReader(sr); // calls #read, so propagates IOException
} catch (IOException e) {
throw new IllegalStateException(e);
}
In this example, the code is propagating IOException
because the API of Reader
is designed to access external state, however we know that StringReader
implementation does not access external state. At this scope, where we can certainly assert that the parts involved in the call don't access IO or any other external state, we can safely rethrow the exception as a runtime exception without astonishing colleagues who are unaware of our implementation (and are possibly assuming that IO-accessing code will throw an IOException
).
The reason for strictly keeping external state dependent exceptions checked is that they are non-deterministic (unlike logic dependent exceptions, which will predictably be reproduced every time for a version of the code). For example, if you try to divide by 0, you will always produce an exception. If you don't divide by 0, you will never produce an exception, and you don't have to handle that exception case, because it will never happen. In the case of accessing a file, however, succeeding once does not mean that you will succeed next time -- the user might have changed permissions, another process might have deleted or modified it. So you always have to handle that exceptional case, or you likely have a bug.

- 538
- 4
- 5
I would like to get comments on this, but I find there are times when this isn't necessarily bad practice. (Or terribly bad). But maybe i am wrong.
Often times an API you are using will throw an exception that you can't imagine actually being thrown in your specific usecase. In this case, it seems perfectly fine to throw a RuntimeException with the caught exception as the cause. If this exception is thrown, it'll likely be the cause of programming error and isn't inside the bounds for correct specification.
Assuming the RuntimeException isn't later caught and ignored, it's no where near an OnErrorResumeNext.
The OnErrorResumeNext would occur when someone catches an exception and simply ignores it or just prints it out. This is terribly bad practice in almost all cases.

- 1,169
- 9
- 13
-
This might be the case near the top of the call tree, where the only thing you can do is try to recover gracefully and knowing the specific error won't really help. In that case, you may have to record the error and move on (process next record, inform user that an error occurred, etc). Otherwise, no. You should always handle exceptions as close to the error as is practical, not wrap them up as a white elephant for the next handler. – Michael K Nov 23 '11 at 19:47
-
@MichaelK The problem is "as close to the error as is practical" in practice often means "through several intervening layers which are out of your direct control". For example, if my class has to implement a certain interface, my hands are tied. That can happen arbitrarily deep in the call tree. Even when the interfaces are under my control, adding throws declarations can make the abstraction leaky if there are only a limited set of concrete implementations that can conceivably throw. Making every client pay the cost for the implementation details of a few is not a great design tradeoff IMO. – Tim Seguine May 10 '17 at 15:20
For standalone applications. When you know your application cannot handle the exception you could, instead of throwing the checked RuntimeException, throw Error, let the application crash, hope for bug-reports, and fix your application. (See the answer of mrmuggles for a more in depth discussion of the pro's and con's of checked versus unchecked.)

- 2,636
- 1
- 16
- 32
This is common practice in many frameworks. E.g. Hibernate
does exactly this. The idea is that the APIs should not be intrusive for client side and Exception
are intrusive since you must explicitly write code to handle them at that place where you call the api. But that place might not be the right place to handle the exception in the first place.
Actually to be honest this is a "hot" topic and many dispute so I will not take a side but I will say that what your friend does/proposes is not un-ordinary or uncommon.

- 1,834
- 3
- 17
- 18
The whole "checked exception" thing is a bad idea.
Structured programming only allows information to be passed between functions (or, in Java parlance, methods) when they are "nearby". More precisely, information can only move across functions in two ways:
From a caller to a callee, via argument passing.
From a callee to its caller, as return values.
This is a fundamentally good thing. This is what allows you to reason about your code locally: if you need to understand or modify a part of your program, you only need to look at that part and other "nearby" ones.
However, in some circumstances, it is necessary to send information to a "distant" function, without anyone in the middle "knowing". This is precisely when exceptions have to be used. An exception is a secret message sent from a raiser (whatever part of your code might contain a throw
statement) to a handler (whatever part of your code might contain a catch
block that is compatible with the exception that was throw
n).
Checked exceptions destroy the secrecy of the mechanism, and, with it, the very reason for its existence. If a function can afford to let its caller "know" a piece of information, just send that piece of information directly as a part of the return value.

- 508
- 2
- 12
-
It might be good to mention that this sort of issue can really wreak havoc in cases where a method runs a function which is supplied by its caller. The author of the method receiving the function will in many cases have no reason to know nor care what the caller is expecting it to do, nor what exceptions the caller might be expecting. If the code receiving the method isn't expecting it to throw a checked exception, the method being supplied may have to wrap any checked exceptions it would throw in unchecked exceptions that its supplier could then catch. – supercat Jul 27 '15 at 18:06
In a boolean question, it is hard to answer differently after two controversial answers, but I would like to give you a perspective that even mentioned in few places, it was not stressed enough for the importance it has.
With the years I found that always someone is confused about a trivial problem they are lacking understanding of some of the fundamentals.
Layering. A software application (at least supposed to be) a pile of layers one on top of another. One important expectation for good layering is that lower layers provide functionality for potentially multiple components from the upper layer.
Let's say your app has the following layers from the bottom up NET, TCP, HTTP, REST, DATA MODEL, BUSINESS.
If your business layer would like to execute a rest call ... wait for a second. Why did I say that? Why did I not say HTTP request or TCP transaction or send network packages? Because those are irrelevant for my business layer. I am not going to handle them, I am not going to look in the details of them. I am perfectly ok if they are deep in the exceptions I get as a cause and I do not want to know that they even exist.
What is more, it is bad if I do know details, because if tomorrow I would like to change the underlining transport protocols dealing with details that are specific to the TCP protocol means that my REST abstraction did not do a good job to abstract itself from the specific implementation.
When transitioning an exception up from layer to layer it is important to revisit every aspect of it and what sense it will make for the abstraction the current layer provides. It might be to replace the exception with other, it might combine several exceptions. It might also transition them from checked to unchecked or vise versa.
Of course, is the actual places you mentioned make sense is a different story, but in general - yes, it could be a good thing to do.

- 264
- 3
- 8
This might depend on case to case basis. In certain scenarios it is wise to do what your friend is doing, for example when you are exposing an api for some clients and you want the client to be least aware of the implementation details, where you know that certain implementation exceptions may be specific to implementation details and not exposable to the client.
By keeping the checked exceptions out of the way, you can expose api's that would enable the client to write cleaner code as the client itself might be pre-validating the exceptional conditions.
For example Integer.parseInt(String) takes a string and returns the integer equivalent of it and throws NumberFormatException in case the string is not numeric. Now imagine a form submission with a field age
is converted through this method but the client would have already ensured validation on its part, so there's no point forcing the check of exception.
There are really a couple of questions here
- Should you transform checked exceptions into unchecked ones?
The general rule of thumb is that exceptions that the caller is expected to catch and recover from should be checked. Other exceptions (ones where the only reasonable outcome is to abort the whole operation or where you consider them unlikely enough that worrying about handling them specifically is not worth it) should be unchecked.
Sometimes your judgement on whether an exception deserves catching and recovery is different from that of the API you are working with. Sometimes context matters, an exception that is worth handling in one situation may not be worth handling in another. Sometimes your hand is forced by existing interfaces. So yes there are legitimate reasons to turn a checked exception into an unchecked exception (or to a different type of checked exception)
- If you are going to turn an unchecked exception into a checked exception how should you do it.
Firstly and most importantly make sure you use the exception chaining facility. That way the information from the original exception is not lost and can be used for debugging.
Secondly you have to decide what exception type to use. Using a plain runtimeexception makes it harder for the caller to determine what went wrong but if the caller is trying to determine what went wrong that may be an indication that you should not have changed the exception to make it unchecked.

- 2,125
- 9
- 15
In my opinion,
In the framework level, we should be catch runtime exceptions to reduce more block of try catch to the invoker in the same place.
In the application level, we rarely capture runtime exceptions and i think this practice was bad.

- 29
- 1
-
1
-
If there is a UI layer in the framework that can handle the exceptions, then the UI would present an error message of some sort that something went wrong. In the case of an one-page javascript app, the app could present an error message. Granted, the UI layer should handle the error only if a deeper layer really can't recover from the error. – Jake Toronto Oct 03 '14 at 17:14