[The Java Posse] Re: How do YOU handle Exceptions?
But that code snippet is horrible; you should never catch an exception and 'just log it' - ONLY the very top level should ever do that. Secondly, if you do log-and-swallow, then whatever the heck you do, don't continue with your method! On Aug 24, 1:21 am, Martin Wildam mwil...@gmail.com wrote: On Aug 23, 11:39 am, Reinier Zwitserloot reini...@gmail.com wrote: A full and exhaustive treatise doesn't exist, but there are a few rules almost everyone can agree with, and yet these rules are not followed by the JDK, probably because we didn't know any better back then. i.e.: [...] Thanks for the compact listing the best practices for using checked exceptions! The ten commandments are also very old posts Mixing religion into talk about programming is a very bad idea. But, I'll take your point that just because something is old does not mean it's wrong. That's what I meant. So, why are you liking Joel's post so much? The only alternative he offers is something that boils down to maybees. [...] A Maybe is simply an alternate form of null: I like his post because he points out that Exceptions are some form of goto statements but being worse in the way that you often can't say without detailed analysis from where the goto will be triggered. Thanks for your explanation of the maybe - I have some methods where I use the null result in case of error. In the past (even before using Java) I have used a common accessible error object (containing status information and error/warning message lists) - a static one accessible from and for all levels within my application. Oh, yeah, that'll go over real well with threading. If I have a process that is spawn into several threads it is indeed that at the end I want to have a single status if the whole process was successful or not. - But I agree with you that in a lot of cases you need separate handling for separate threads. Yesterday when going to bed I spent still a longer time thinking about the error handling in general. Peter painting the picture with the UML chart with and without error handling was very impressive. Maybe we should look at error handling from different point of views. First, there is the very normal dummy user who don't have a clue on what is there running in the background. Second there is a system administrator who - if something goes wrong - could see whether there might be a problem with the environment or with the configuration he is responsible for. And then there is the developer who wants/needs comprehensive detailed information if there is a doubt that an upcoming error might be due to a bug. The dummy user is usually overwhelmed if you present comprehensive information (or a stack trace for example). He/She wants a simple message - e.g. like Google Calender's Ooops, some calenders could not be loaded. Try again later. - I think basically every IOException could result in such a final handling. The administrator wants some more information, like if a host could not be reached or name could not be resolved etc. The developer is the only person interested in stack traces for instance. I think a solution for the different interests could be a proper inheritance model of exceptions that you are using in your applications. This means, if an exception occurs I can handle it using the first parent exception to generate the operation failed thing and for the developer log the exact detail exception that occurred. So I could have some common PreCheckException (and children like InputPreCheckException, ConfigurationPreCheckException and so on). The second problem is the coding efficiency and readability. Within a method depending on the exception some object variables might not be set to a valid instance (if you have a longer try-block above and handling just one parent exception). This may result in a lot of null- checking necessary. A solution for this could be that the methods you are calling should always return in a sane way (mostly just avoiding null-pointer-exceptions) if they receive nulls as arguments. Sample: try { checkInputs(myTask); checkEnvironment(myTask); checkConfig(myTask); con = openConnection(myTask);} catch (PreCheckException e) { doLoggingAndMessaging(e); } try { doCoreWork(con, myTask);} catch (ProcessingException e) { doLoggingAndMessaging(e); } closeConnection(con); In that sample doCoreWork should fail if con is null or myTask is missing some important data/status that it should have got during the prechecks. The closeConnection method on the other hand should not throw another exception but silently finish if no (open) connection is given - just as well there is nothing to do for me. Such a thing looks quite clean to me. Just my - not verified - ideas. --~--~-~--~~~---~--~~ You received this message because you are subscribed to
[The Java Posse] Re: How do YOU handle Exceptions?
Martin Wildam wrote: [...] Maybe we should look at error handling from different point of views. First, there is the very normal dummy user who don't have a clue on what is there running in the background. Second there is a system administrator who - if something goes wrong - could see whether there might be a problem with the environment or with the configuration he is responsible for. And then there is the developer who wants/needs comprehensive detailed information if there is a doubt that an upcoming error might be due to a bug. The dummy user is usually overwhelmed if you present comprehensive information (or a stack trace for example). He/She wants a simple message - e.g. like Google Calender's Ooops, some calenders could not be loaded. Try again later. - I think basically every IOException could result in such a final handling. The administrator wants some more information, like if a host could not be reached or name could not be resolved etc. The developer is the only person interested in stack traces for instance. I think a solution for the different interests could be a proper inheritance model of exceptions that you are using in your applications. This means, if an exception occurs I can handle it using the first parent exception to generate the operation failed thing and for the developer log the exact detail exception that occurred. So I could have some common PreCheckException (and children like InputPreCheckException, ConfigurationPreCheckException and so on). I think sometimes the same exception can be required to be looked at in different ways. While the user should always get some high-level we are sorry message, the admin/developer distinction is not necessarily nicely along a hierarchy you describe. In fact some of the lowest exceptions could be of a nature that administrators have to resolve. Things get even more complicated if the boundaries are blurry. I've seen that many times with smaller projects and I believe it is still common at Amazon: the developers are also administrators. There can be quite different logging setups depending on your organizational structure, auditing needs and other aspects. That's where external logging configurations come into play. And don't forget that there are at least two dimensions: the hierarchy and the chaining. I tend to chain exceptions through the abstraction layers while using the hierarchies to model different level of detail within a layer. In some way I like the idea of a higher level error reporting system where the user interface is not just plain text but allows drilling down into the information, ideally with structure data in the exceptions. I've seen such systems used in various places (although not with much structured data). In some way the Windows error log is one, but I have also seen logging handlers that log into a full-blown database or a ticket system. The problem is that you really want your logging to be easy and reliable, which those system often are not. But even in text format you can gain a lot by making sure your exception message is written well and with enough information to identify the real issue without wading through stack traces (as a developer) or guru meditation (everyone). The second problem is the coding efficiency and readability. Within a method depending on the exception some object variables might not be set to a valid instance (if you have a longer try-block above and handling just one parent exception). This may result in a lot of null- checking necessary. A solution for this could be that the methods you are calling should always return in a sane way (mostly just avoiding null-pointer-exceptions) if they receive nulls as arguments. Sample: try { checkInputs(myTask); checkEnvironment(myTask); checkConfig(myTask); con = openConnection(myTask); } catch (PreCheckException e) { doLoggingAndMessaging(e); } try { doCoreWork(con, myTask); } catch (ProcessingException e) { doLoggingAndMessaging(e); } closeConnection(con); In that sample doCoreWork should fail if con is null or myTask is missing some important data/status that it should have got during the prechecks. The closeConnection method on the other hand should not throw another exception but silently finish if no (open) connection is given - just as well there is nothing to do for me. Such a thing looks quite clean to me. Just my - not verified - ideas This approach can help sometimes, in particular if you can model your system in such a way that the prechecked-objects have only safe methods (modulo the usual candidates you can hardly avoid such as running out of memory). But I don't think this is always feasible, e.g. if you do processing on a database you either have to have a lot of memory to buffer data or you have to live with the fact that the network can cause trouble at any time during your processing. But
[The Java Posse] Re: How do YOU handle Exceptions?
What about the signal-to-noise aspect? I find that to be annoying with logging and the only sane reason to use AOP. However since I have an issue with complexity and library creep, I prefer to simply have a NetBeans plugin suppress the font color of logging statements. In the perfect world, the IDE would be capable of masking these aspects - not totally unlike what Lombok is attempting. /Casper On 24 Aug., 14:05, Peter Becker peter.becker...@gmail.com wrote: Martin Wildam wrote: [...] Maybe we should look at error handling from different point of views. First, there is the very normal dummy user who don't have a clue on what is there running in the background. Second there is a system administrator who - if something goes wrong - could see whether there might be a problem with the environment or with the configuration he is responsible for. And then there is the developer who wants/needs comprehensive detailed information if there is a doubt that an upcoming error might be due to a bug. The dummy user is usually overwhelmed if you present comprehensive information (or a stack trace for example). He/She wants a simple message - e.g. like Google Calender's Ooops, some calenders could not be loaded. Try again later. - I think basically every IOException could result in such a final handling. The administrator wants some more information, like if a host could not be reached or name could not be resolved etc. The developer is the only person interested in stack traces for instance. I think a solution for the different interests could be a proper inheritance model of exceptions that you are using in your applications. This means, if an exception occurs I can handle it using the first parent exception to generate the operation failed thing and for the developer log the exact detail exception that occurred. So I could have some common PreCheckException (and children like InputPreCheckException, ConfigurationPreCheckException and so on). I think sometimes the same exception can be required to be looked at in different ways. While the user should always get some high-level we are sorry message, the admin/developer distinction is not necessarily nicely along a hierarchy you describe. In fact some of the lowest exceptions could be of a nature that administrators have to resolve. Things get even more complicated if the boundaries are blurry. I've seen that many times with smaller projects and I believe it is still common at Amazon: the developers are also administrators. There can be quite different logging setups depending on your organizational structure, auditing needs and other aspects. That's where external logging configurations come into play. And don't forget that there are at least two dimensions: the hierarchy and the chaining. I tend to chain exceptions through the abstraction layers while using the hierarchies to model different level of detail within a layer. In some way I like the idea of a higher level error reporting system where the user interface is not just plain text but allows drilling down into the information, ideally with structure data in the exceptions. I've seen such systems used in various places (although not with much structured data). In some way the Windows error log is one, but I have also seen logging handlers that log into a full-blown database or a ticket system. The problem is that you really want your logging to be easy and reliable, which those system often are not. But even in text format you can gain a lot by making sure your exception message is written well and with enough information to identify the real issue without wading through stack traces (as a developer) or guru meditation (everyone). The second problem is the coding efficiency and readability. Within a method depending on the exception some object variables might not be set to a valid instance (if you have a longer try-block above and handling just one parent exception). This may result in a lot of null- checking necessary. A solution for this could be that the methods you are calling should always return in a sane way (mostly just avoiding null-pointer-exceptions) if they receive nulls as arguments. Sample: try { checkInputs(myTask); checkEnvironment(myTask); checkConfig(myTask); con = openConnection(myTask); } catch (PreCheckException e) { doLoggingAndMessaging(e); } try { doCoreWork(con, myTask); } catch (ProcessingException e) { doLoggingAndMessaging(e); } closeConnection(con); In that sample doCoreWork should fail if con is null or myTask is missing some important data/status that it should have got during the prechecks. The closeConnection method on the other hand should not throw another exception but silently finish if no (open) connection is given - just as well there is nothing to do for me. Such a thing looks
[The Java Posse] Re: How do YOU handle Exceptions?
It's not out of band, Peter - this stuff happens, in real life, even if you never explicitly accepted the burden of responsibility by e.g. using @SneakyThrows. Just mixing class files compiled against different versions of the same code base is enough to get there. Thus, you *CANNOT* just swallow exceptions. I was not referring to your 'Ex' as standing specifically for java.lang.Exception - it doesn't matter what exception class it stands for. Swallowing an exception automatically behind the scenes is not acceptable. At the very least wrap it up (not my preferred solution, certainly, but better than swallowing it). On Aug 22, 11:53 am, Peter Becker peter.becker...@gmail.com wrote: I think I might have caused some confusion by being too lazy: Ex is meant to be a particular checked exception, not a shorthand for Exception. If you are referring to your sneaky throws: I consider them out of scope. There are many ways to subvert Java code, particularly if reflection is allowed. If anyone throws a checked exception in code that was explicitly designed not to throw it (after all that is what the safe/unsafe distinction is for), then so be it. Java is not strong enough to stop someone with that attitude from breaking things. Peter Reinier Zwitserloot wrote: Peter, your code sample is very much broken - exceptions are just silently swallowed in the safe version. Sure, you declared that the exception can't happen, but as I've mentioned a few times already, because checked exceptions aren't enforced on the JVM level, they can occur at _any_ time. Therefore, occasionally, such code would swallow an exception. No good. I'm fairly sure that turning every java method into BGGA-style throws containing generics is going to be just as annoying, if not far worse, than the current situation. The problem with checked exceptions is that all implementations so far suck far worse than they help. I remain convinced that java's checked exception system with an explicit command to get around the checked exception system is the most practical (though it is of course not the most elegant). On Aug 21, 11:43 am, Peter Becker peter.becker...@gmail.com wrote: As I said: in cases where you want to have a version of your code where the exception bubbles up and one where it doesn't you'll get the duplication. I think that is usually a bad idea, although I must admit the wrapper case you describe is an exception since the layer is the same. I don't see that problem spread too far, though. If your code is really that big, I'd even consider this: public class UnsafeWrapper implements UnsafeInterface { protected UnsafeInterface orig; ... public doAction() throws Ex { ... orig.doAction(); } } public class SafeWrapper implements SafeInterface { ... public doAction() { ... try { orig.doAction(); // call on UnsafeWrapper.doAction() } catch(Ex e) { // won't happen } } } Not very elegant, but avoids major duplication. I believe that with union types the whole problem would disappear since the subtyping would allow using generics to create the different versions. As long as exceptions are not part of the type signature it won't happen in Java. Peter Reinier Zwitserloot wrote: Peter, I still don't see how that'll avoid code duplication. Let's say, for argument's sake, that a FilterInputStream's read() method contains 4 pages of complex code. This code calls back into the filtered stream's read method loads of times. How would we avoid duplicating these 4 pages if we want 2 types of FilterInputStream: One that wraps a Safe InputStream and does not throw IOException, and one that wraps an unsafe InputStream and does throw IOException. On Aug 20, 9:36 am, Peter Becker peter.becker...@gmail.com wrote: Here you go (three files): = test/Unsafe.java== package test; import java.io.IOException; public interface Unsafe { void method() throws IOException; } = test/Safe.java == package test; public interface Safe extends Unsafe { void method(); } =test/Test.java=== package test; import java.io.IOException; public class Test { class UnsafeImpl implements Unsafe { @Override public void method() throws IOException { throw new IOException(); // ok } }; class SafeImpl implements Safe { @Override public void method() { // can't throw here } }; void method1(Unsafe unsafe) { unsafe.method(); // error, need to deal with exception } void method2(Safe safe) { safe.method(); // ok } } == The one trick is to realize that the safe version is actually the more specific one. If
[The Java Posse] Re: How do YOU handle Exceptions?
On Aug 23, 12:52 am, Martin Wildam mwil...@gmail.com wrote: In reality programmers could live without exceptions for many, many years. ;-) We all coded assembly too. You're flipping the argument around now, Martin: Just because something is old, it's true. That's just as logically invalid as 'Something is old, therefore its false'. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
On Aug 23, 11:39 am, Reinier Zwitserloot reini...@gmail.com wrote: A full and exhaustive treatise doesn't exist, but there are a few rules almost everyone can agree with, and yet these rules are not followed by the JDK, probably because we didn't know any better back then. i.e.: [...] Thanks for the compact listing the best practices for using checked exceptions! The ten commandments are also very old posts Mixing religion into talk about programming is a very bad idea. But, I'll take your point that just because something is old does not mean it's wrong. That's what I meant. So, why are you liking Joel's post so much? The only alternative he offers is something that boils down to maybees. [...] A Maybe is simply an alternate form of null: I like his post because he points out that Exceptions are some form of goto statements but being worse in the way that you often can't say without detailed analysis from where the goto will be triggered. Thanks for your explanation of the maybe - I have some methods where I use the null result in case of error. In the past (even before using Java) I have used a common accessible error object (containing status information and error/warning message lists) - a static one accessible from and for all levels within my application. Oh, yeah, that'll go over real well with threading. If I have a process that is spawn into several threads it is indeed that at the end I want to have a single status if the whole process was successful or not. - But I agree with you that in a lot of cases you need separate handling for separate threads. Yesterday when going to bed I spent still a longer time thinking about the error handling in general. Peter painting the picture with the UML chart with and without error handling was very impressive. Maybe we should look at error handling from different point of views. First, there is the very normal dummy user who don't have a clue on what is there running in the background. Second there is a system administrator who - if something goes wrong - could see whether there might be a problem with the environment or with the configuration he is responsible for. And then there is the developer who wants/needs comprehensive detailed information if there is a doubt that an upcoming error might be due to a bug. The dummy user is usually overwhelmed if you present comprehensive information (or a stack trace for example). He/She wants a simple message - e.g. like Google Calender's Ooops, some calenders could not be loaded. Try again later. - I think basically every IOException could result in such a final handling. The administrator wants some more information, like if a host could not be reached or name could not be resolved etc. The developer is the only person interested in stack traces for instance. I think a solution for the different interests could be a proper inheritance model of exceptions that you are using in your applications. This means, if an exception occurs I can handle it using the first parent exception to generate the operation failed thing and for the developer log the exact detail exception that occurred. So I could have some common PreCheckException (and children like InputPreCheckException, ConfigurationPreCheckException and so on). The second problem is the coding efficiency and readability. Within a method depending on the exception some object variables might not be set to a valid instance (if you have a longer try-block above and handling just one parent exception). This may result in a lot of null- checking necessary. A solution for this could be that the methods you are calling should always return in a sane way (mostly just avoiding null-pointer-exceptions) if they receive nulls as arguments. Sample: try { checkInputs(myTask); checkEnvironment(myTask); checkConfig(myTask); con = openConnection(myTask); } catch (PreCheckException e) { doLoggingAndMessaging(e); } try { doCoreWork(con, myTask); } catch (ProcessingException e) { doLoggingAndMessaging(e); } closeConnection(con); In that sample doCoreWork should fail if con is null or myTask is missing some important data/status that it should have got during the prechecks. The closeConnection method on the other hand should not throw another exception but silently finish if no (open) connection is given - just as well there is nothing to do for me. Such a thing looks quite clean to me. Just my - not verified - ideas. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
I can't let this horse puckey about 'exceptions are less readable' stand. It's hogwash. Consider that any operation, anywhere in the entirety of your java source base, can throw just about any exception. Not just theoretically, but practically: You can get an OutOfMemoryError, or a ClassNotFoundError, for example. Actually trying to shove these status conditions into some sort of return object that tracks exactly what went right and what went wrong is *PHENOMENALLY* more boilerplate than even java's verbose checked exception system. I take it as axiomatic that returning an integer that holds an error code is utterly insane. At best you can make an argument that you ought to keep exceptions for the very exceptional, and to push the line between 'exceptional' and 'alternative exit condition' as far to the exceptional side as you can; e.g all file operations ought to return a FileOperationResult object. But, I put it to you: How happy would you really be with such an API? Because it exists, folks. java.io.File. Instead of throwing exceptions, it returns booleans. And it's so hated, its getting replaced in java 7. It's been tried, it's failed miserably. You'd have to return an object that states the exact problem that actually occurred, and, at that point, aren't you just writing the equivalent of: public IOException mkdir() {}? whether the IOException is returned normally (or, more likely, in the case of a method that also needs to return some actual data, as an Either and you'd have to query the Either to figure out what happened - d'oh) or 'returned' via the exception mechanism is relatively speaking a very small point. A much bigger point is that you just can't get around the notion that you NEED some sort of exception system to handle the truly exceptional - unless we'd all prefer going back to the 'core dumped' days, and that there's a real need to have semi-exceptional conditions that you'd like, by default, to walk up the stack quite a bit before being handled. Here, simple example: You write a servlet, and something untoward happens - say, a database issue (SQLException). In plenty of situations you don't want your servlet to handle it - you want that problem to walk up the stack, back to the servlet container that knows to return a 500, log something, and maybe try to notify an administrator. It would be hopeless if you had to rely on the serlvet to pass through problems. It would also make changing APIs to add new flavours of the exceptional much more problematic, and as theoretically sound it seems to say: But public APIs shouldn't ever change! - that's not very practical. The exceptional stuff is the first thing APIs are likely to change, exactly because it is so closely related to implementation details. Joel was dead wrong. On Aug 21, 3:40 pm, Martin Wildam mwil...@gmail.com wrote: On Aug 21, 2:07 pm, Peter Becker peter.becker...@gmail.com wrote: I take the point that it is possible to make code harder to read using exceptions in a way that is not possible without. I must admit I didn't really think it through when I read Joel's blog post. I think the reduced readability is the core disadvantage of using Exceptions. And I think that it is easier to create buggy code with exceptions - especially for beginners. (I know that most of those doing Java do it since a long while but they get older and junger people must somehow follow them). There is the opposite danger, though: ignoring a return value. Since C-like languages allow functions to be called as statements, it is pretty easy to just ignore the fact that there is an error code returned. Checked exceptions force you to deal with the issue. Whether it is an exception or a return code you always can drop it or deal with it. When I use a method like openFile or something the first thing automatically is to look for a return code. Of course that problem could also be fixed by disallowing calling functions as statements, which I think would be a good idea not just for this reason. I would loose then the option to ignore the result which may make sense (e.g. loading an optional configuration file). People want closures, annotations and all the like but then I should get limited how to use a simple method? Best regards, Martin. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Peter, your code sample is very much broken - exceptions are just silently swallowed in the safe version. Sure, you declared that the exception can't happen, but as I've mentioned a few times already, because checked exceptions aren't enforced on the JVM level, they can occur at _any_ time. Therefore, occasionally, such code would swallow an exception. No good. I'm fairly sure that turning every java method into BGGA-style throws containing generics is going to be just as annoying, if not far worse, than the current situation. The problem with checked exceptions is that all implementations so far suck far worse than they help. I remain convinced that java's checked exception system with an explicit command to get around the checked exception system is the most practical (though it is of course not the most elegant). On Aug 21, 11:43 am, Peter Becker peter.becker...@gmail.com wrote: As I said: in cases where you want to have a version of your code where the exception bubbles up and one where it doesn't you'll get the duplication. I think that is usually a bad idea, although I must admit the wrapper case you describe is an exception since the layer is the same. I don't see that problem spread too far, though. If your code is really that big, I'd even consider this: public class UnsafeWrapper implements UnsafeInterface { protected UnsafeInterface orig; ... public doAction() throws Ex { ... orig.doAction(); } } public class SafeWrapper implements SafeInterface { ... public doAction() { ... try { orig.doAction(); // call on UnsafeWrapper.doAction() } catch(Ex e) { // won't happen } } } Not very elegant, but avoids major duplication. I believe that with union types the whole problem would disappear since the subtyping would allow using generics to create the different versions. As long as exceptions are not part of the type signature it won't happen in Java. Peter Reinier Zwitserloot wrote: Peter, I still don't see how that'll avoid code duplication. Let's say, for argument's sake, that a FilterInputStream's read() method contains 4 pages of complex code. This code calls back into the filtered stream's read method loads of times. How would we avoid duplicating these 4 pages if we want 2 types of FilterInputStream: One that wraps a Safe InputStream and does not throw IOException, and one that wraps an unsafe InputStream and does throw IOException. On Aug 20, 9:36 am, Peter Becker peter.becker...@gmail.com wrote: Here you go (three files): = test/Unsafe.java== package test; import java.io.IOException; public interface Unsafe { void method() throws IOException; } = test/Safe.java == package test; public interface Safe extends Unsafe { void method(); } =test/Test.java=== package test; import java.io.IOException; public class Test { class UnsafeImpl implements Unsafe { @Override public void method() throws IOException { throw new IOException(); // ok } }; class SafeImpl implements Safe { @Override public void method() { // can't throw here } }; void method1(Unsafe unsafe) { unsafe.method(); // error, need to deal with exception } void method2(Safe safe) { safe.method(); // ok } } == The one trick is to realize that the safe version is actually the more specific one. If you think of the exception in terms of the type union (not accurate, but a decent analogy), then Unsafe.method() returns void|IOException while Safe.method() returns void, which is a more specific type, thus the return types are co-variant. More generally you can argue that Safe.method() makes stronger guarantees about its behavior than Unsafe.method(), so subtyping is legal. Apart from the one marked position the code above is legal Java. Peter Reinier Zwitserloot wrote: On Aug 20, 12:21 am, Peter Becker peter.becker...@gmail.com wrote: No implementation would be duplicated, the safe version could be a subtype of the unsafe one. Not too many interfaces will face that problem. To me it seems much better than not distinguishing. Can you show me how this would work? I have a hard time seeing how you can do that without (oh, the irony), employing some sort of sneakythrow mechanism. I guess we will have to agree to disagree here, but I'm fairly sure the idealism lost in allowing sneakythrow is minor, whereas the amount of pain you can solve is sizable. (in practice, due to widespread bad API design we all know will never ever get fixed, such as in the core JDK) --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google
[The Java Posse] Re: How do YOU handle Exceptions?
I think I might have caused some confusion by being too lazy: Ex is meant to be a particular checked exception, not a shorthand for Exception. If you are referring to your sneaky throws: I consider them out of scope. There are many ways to subvert Java code, particularly if reflection is allowed. If anyone throws a checked exception in code that was explicitly designed not to throw it (after all that is what the safe/unsafe distinction is for), then so be it. Java is not strong enough to stop someone with that attitude from breaking things. Peter Reinier Zwitserloot wrote: Peter, your code sample is very much broken - exceptions are just silently swallowed in the safe version. Sure, you declared that the exception can't happen, but as I've mentioned a few times already, because checked exceptions aren't enforced on the JVM level, they can occur at _any_ time. Therefore, occasionally, such code would swallow an exception. No good. I'm fairly sure that turning every java method into BGGA-style throws containing generics is going to be just as annoying, if not far worse, than the current situation. The problem with checked exceptions is that all implementations so far suck far worse than they help. I remain convinced that java's checked exception system with an explicit command to get around the checked exception system is the most practical (though it is of course not the most elegant). On Aug 21, 11:43 am, Peter Becker peter.becker...@gmail.com wrote: As I said: in cases where you want to have a version of your code where the exception bubbles up and one where it doesn't you'll get the duplication. I think that is usually a bad idea, although I must admit the wrapper case you describe is an exception since the layer is the same. I don't see that problem spread too far, though. If your code is really that big, I'd even consider this: public class UnsafeWrapper implements UnsafeInterface { protected UnsafeInterface orig; ... public doAction() throws Ex { ... orig.doAction(); } } public class SafeWrapper implements SafeInterface { ... public doAction() { ... try { orig.doAction(); // call on UnsafeWrapper.doAction() } catch(Ex e) { // won't happen } } } Not very elegant, but avoids major duplication. I believe that with union types the whole problem would disappear since the subtyping would allow using generics to create the different versions. As long as exceptions are not part of the type signature it won't happen in Java. Peter Reinier Zwitserloot wrote: Peter, I still don't see how that'll avoid code duplication. Let's say, for argument's sake, that a FilterInputStream's read() method contains 4 pages of complex code. This code calls back into the filtered stream's read method loads of times. How would we avoid duplicating these 4 pages if we want 2 types of FilterInputStream: One that wraps a Safe InputStream and does not throw IOException, and one that wraps an unsafe InputStream and does throw IOException. On Aug 20, 9:36 am, Peter Becker peter.becker...@gmail.com wrote: Here you go (three files): = test/Unsafe.java== package test; import java.io.IOException; public interface Unsafe { void method() throws IOException; } = test/Safe.java == package test; public interface Safe extends Unsafe { void method(); } =test/Test.java=== package test; import java.io.IOException; public class Test { class UnsafeImpl implements Unsafe { @Override public void method() throws IOException { throw new IOException(); // ok } }; class SafeImpl implements Safe { @Override public void method() { // can't throw here } }; void method1(Unsafe unsafe) { unsafe.method(); // error, need to deal with exception } void method2(Safe safe) { safe.method(); // ok } } == The one trick is to realize that the safe version is actually the more specific one. If you think of the exception in terms of the type union (not accurate, but a decent analogy), then Unsafe.method() returns void|IOException while Safe.method() returns void, which is a more specific type, thus the return types are co-variant. More generally you can argue that Safe.method() makes stronger guarantees about its behavior than Unsafe.method(), so subtyping is legal. Apart from the one marked position the code above is legal Java. Peter Reinier Zwitserloot wrote: On Aug 20, 12:21 am, Peter Becker peter.becker...@gmail.com wrote: No
[The Java Posse] Re: How do YOU handle Exceptions?
After initially disagreeing completely I can see a point in that exceptions break the normal control flow and can thus cause surprising behavior. But I agree with you that the alternatives aren't necessarily better. Somehow error handling is never easy. Just take one of these nice graphical displays of code execution (UML, workflows) and add the error handling in. Particularly in workflows your nice and simple graph suddenly turns into a mess. The same is true on the code level: code that is pretty straightforward for the normal case can quickly turn into a mess once error handling is added, no matter what system of error handling you use. One note: I think you could probably write a system where most common technical errors are handled via return values, but you would need to have a lot of unions/eithers. That approach is quite comparable to the checked exceptions (I have done this comparison the other way around before), but the control flow is quite different. The File class in Java stands out so much since it is different, but it might just work somewhere else. Peter Reinier Zwitserloot wrote: I can't let this horse puckey about 'exceptions are less readable' stand. It's hogwash. Consider that any operation, anywhere in the entirety of your java source base, can throw just about any exception. Not just theoretically, but practically: You can get an OutOfMemoryError, or a ClassNotFoundError, for example. Actually trying to shove these status conditions into some sort of return object that tracks exactly what went right and what went wrong is *PHENOMENALLY* more boilerplate than even java's verbose checked exception system. I take it as axiomatic that returning an integer that holds an error code is utterly insane. At best you can make an argument that you ought to keep exceptions for the very exceptional, and to push the line between 'exceptional' and 'alternative exit condition' as far to the exceptional side as you can; e.g all file operations ought to return a FileOperationResult object. But, I put it to you: How happy would you really be with such an API? Because it exists, folks. java.io.File. Instead of throwing exceptions, it returns booleans. And it's so hated, its getting replaced in java 7. It's been tried, it's failed miserably. You'd have to return an object that states the exact problem that actually occurred, and, at that point, aren't you just writing the equivalent of: public IOException mkdir() {}? whether the IOException is returned normally (or, more likely, in the case of a method that also needs to return some actual data, as an Either and you'd have to query the Either to figure out what happened - d'oh) or 'returned' via the exception mechanism is relatively speaking a very small point. A much bigger point is that you just can't get around the notion that you NEED some sort of exception system to handle the truly exceptional - unless we'd all prefer going back to the 'core dumped' days, and that there's a real need to have semi-exceptional conditions that you'd like, by default, to walk up the stack quite a bit before being handled. Here, simple example: You write a servlet, and something untoward happens - say, a database issue (SQLException). In plenty of situations you don't want your servlet to handle it - you want that problem to walk up the stack, back to the servlet container that knows to return a 500, log something, and maybe try to notify an administrator. It would be hopeless if you had to rely on the serlvet to pass through problems. It would also make changing APIs to add new flavours of the exceptional much more problematic, and as theoretically sound it seems to say: But public APIs shouldn't ever change! - that's not very practical. The exceptional stuff is the first thing APIs are likely to change, exactly because it is so closely related to implementation details. Joel was dead wrong. On Aug 21, 3:40 pm, Martin Wildam mwil...@gmail.com wrote: On Aug 21, 2:07 pm, Peter Becker peter.becker...@gmail.com wrote: I take the point that it is possible to make code harder to read using exceptions in a way that is not possible without. I must admit I didn't really think it through when I read Joel's blog post. I think the reduced readability is the core disadvantage of using Exceptions. And I think that it is easier to create buggy code with exceptions - especially for beginners. (I know that most of those doing Java do it since a long while but they get older and junger people must somehow follow them). There is the opposite danger, though: ignoring a return value. Since C-like languages allow functions to be called as statements, it is pretty easy to just ignore the fact that there is an error code returned. Checked exceptions force you to deal with the issue. Whether it is an exception or a return code you always can drop it or deal with
[The Java Posse] Re: How do YOU handle Exceptions?
On Aug 21, 4:46 pm, B Smith-Mannschott bsmith.o...@gmail.com wrote: Checked exceptions *are* a failed experiment. My first experience and after reading Joel's post I was thinking that but previous posters convinced me that this is not necessarily true - but I think there lies some truth also in your comparison with communism. BTW: I find the checked exceptions more useful than the unchecked exceptions (for using in my own code). Some have argued that there's nothing wrong with checked exceptions, per se, it's just that people don't use them right. The question is: How really to use them right? I think this is a desired result of this discussion. :-] Joel's article, I can't really agree with, though it's a pretty old post. Exceptions as an alternate form a control flow have their place. The ten commandments are also very old posts - information or thoughts do not necessarily become less important with increasing age. ;-) - I cannot say that I completely agree with everything in that post, but the point that completely fits my experience is the decreased readability. I wish Java had a good way of dealing with partial functions (i.e. functions that can't return a sensible value for all possible inputs). The only options we seem to have are: throw an exception or return null. Java's null is a mess. (Though sometimes the Null Object Pattern can help here.) Languages with a Maybe type (e.g. Scala) are appealing. Never heard of the Maybe type - but I am pretty sure that a Maybe would be the last thing I would like having to deal with. I like in Python that a function can return multiple values, but something similar can be achieved in Java returning objects. Imagine to return an object that contains a return value + your data. However, if you have very different return types you would need many different new classes encapsulating all the combinations. In the past (even before using Java) I have used a common accessible error object (containing status information and error/warning message lists) - a static one accessible from and for all levels within my application. So my functions can return a value or null and if they produce an error they tell this separately. An advantage is that whoever interested can investigate current error status and a disadvantage is that you have to be careful when to reset error status. But I have used this method quite successful for many years prior using Java. I have started implementing something similar for my Java projects and I think I can improve this method further. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Martin Wildam wrote: On Aug 22, 7:23 am, Peter Becker peter.becker...@gmail.com wrote: While I'm still arguing for checked exceptions, I'm not 100% convinced their good yet either. But nearly every argument I see why they are bad is about how they are used badly, with the conclusion of some intrinsic badness. I agree with you. - But since (at least my opinion) exceptions are either used badly in some of the core Java APIs from Sun the question is really, how to get people - especially beginners - to understand how they are used correctly. Now that is a good question to ask. Unfortunately when teaching about exceptions you will encounter some major poblems: 1) the first encounter with exceptions will be most likely the JDK, i.e. a bad example (and beginner's tend to think the JDK must have the best design ever) 2) to deal with exceptions you need to do the wrong things sometimes unless you avoid the JDK somehow 3) there doesn't seem to be much agreement on how to do it right in the community 4) most people who have experience claim that checked exceptions are intrinsically broken (IMO invalidly) To me it feels like a big case of SNAFU, sustained by Sun's unwillingness to do anything that breaks backwards-compatibility. I think the only thing you can do to teach someone something decent about exceptions is to teach them different error handling approaches in the abstract, and make them aware that in many scenarios error handling can be the most complicated aspect of your code. Someone should probably write a nice book talking only about error handling, the different ways to propagate errors (special return values, checked exceptions, unchecked exceptions, union types) and the different ways to deal with them. A nice chapter on logging strategies would be good, too. Maybe one on the errors you can't handle (stuff such as external errors, infinite loops, infinite recursion, resource leaks). Does anyone know of such a book or volunteer? :-) Peter --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
On 23 Aug., 01:25, Peter Becker peter.becker...@gmail.com wrote: Someone should probably write a nice book talking only about error handling, the different ways to propagate errors (special return values, checked exceptions, unchecked exceptions, union types) and the different ways to deal with them. A nice chapter on logging strategies would be good, too. Maybe one on the errors you can't handle (stuff such as external errors, infinite loops, infinite recursion, resource leaks). Does anyone know of such a book or volunteer? :-) Well if you read best-practice/state-of-the-art books like Clean Code, Code Complete, The Pragmatic Programmer etc. you already get most of that. But this is the complex world of Java, I have no doubt we could see a book on logging frameworks and strategies. That's when I think we need simplicity back so that it won't just be the top 10% reading books, that will be capable of producing quality code. /Casper --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Casper Bang wrote: On 23 Aug., 01:25, Peter Becker peter.becker...@gmail.com wrote: Someone should probably write a nice book talking only about error handling, the different ways to propagate errors (special return values, checked exceptions, unchecked exceptions, union types) and the different ways to deal with them. A nice chapter on logging strategies would be good, too. Maybe one on the errors you can't handle (stuff such as external errors, infinite loops, infinite recursion, resource leaks). Does anyone know of such a book or volunteer? :-) Well if you read best-practice/state-of-the-art books like Clean Code, Code Complete, The Pragmatic Programmer etc. you already get most of that. But this is the complex world of Java, I have no doubt we could see a book on logging frameworks and strategies. That's when I think we need simplicity back so that it won't just be the top 10% reading books, that will be capable of producing quality code. I think error handling strategies transcends languages. The book you listed do that, too -- but even these books tend to focus on the positive cases. Error handling seems to be the one case hardly anyone gets right. Examples for beginners tend to ignore the whole question. Quite often you really don't need to (it can be quite acceptable that your program crashes in rare cases), but if your system is mission or even life critical you suddenly get into a realm that usually no one talks about. Or at least no in those books I've read, which could well be my fault. Peter --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Hello, Let me to say what I think on that topic. Guys If you don't know how to handle exception for a given method then you are better off simply throwing it. Just add it to the method declaration. That's all about that. Handle only exceptions in case you are know for sure how to deal with a failure/error. In some cases you can simply wrap an exception into RuntimeException. It sounds like you convert it to an error intentionally. kinda exception handling. It makes sense for wealth of situations. Don't write useless boilerplate code that in many cases is cause of an error. Keep the things as simple as there are. alexander On Aug 18, 4:55 am, Christian Catchpole christ...@catchpole.net wrote: No, i just let that go up. I really try to avoid the declare as null then set thingy. On Aug 18, 12:03 pm, Casper Bang casper.b...@gmail.com wrote: You neglect to handle the checked exception declared by prepareStatement no? PreparedStatement stmt = null; try{ stmt = connection.prepareStatement(sql); final ResultSet rs = stmt.executeQuery(); try{ while (rs.next()){ // Stuff... { } finally{ rs.close(); }} catch(SQLException e){ // Logging...} finally{ try{ stmt.close(); } catch(SQLException whoTheFuckCares){ }; } Really, how many other ways are there to do it I wonder now? (Apart from wrapping certain things, like the last try-catch clause in some general purpose closer util?). /Casper --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Yep. That's my approach. Guys If you don't know how to handle exception for a given method then you are better off simply throwing it. This sentence may confuse some who will assume they have to catch it in the first place. Maybe a better phrase is: If you don't know how to handle exception for a given method then just don't catch it. Hey, I just had an idea. Why not compile this with Reinier's checkless compiler, jar it up and include it in your normal projects.. public class Throw { public static void unchecked(Throwable throwable) { throw throwable; } } all you need to do, where you would normally wrap the exception in a runtime exception is do this.. public void method() { try { ... } catch (SQLException sqle) { Throw.unchecked(sqle); } } On Aug 21, 6:30 pm, a.efremov a.efre...@javasmith.org wrote: Hello, Let me to say what I think on that topic. Guys If you don't know how to handle exception for a given method then you are better off simply throwing it. Just add it to the method declaration. That's all about that. Handle only exceptions in case you are know for sure how to deal with a failure/error. In some cases you can simply wrap an exception into RuntimeException. It sounds like you convert it to an error intentionally. kinda exception handling. It makes sense for wealth of situations. Don't write useless boilerplate code that in many cases is cause of an error. Keep the things as simple as there are. alexander On Aug 18, 4:55 am, Christian Catchpole christ...@catchpole.net wrote: No, i just let that go up. I really try to avoid the declare as null then set thingy. On Aug 18, 12:03 pm, Casper Bang casper.b...@gmail.com wrote: You neglect to handle the checked exception declared by prepareStatement no? PreparedStatement stmt = null; try{ stmt = connection.prepareStatement(sql); final ResultSet rs = stmt.executeQuery(); try{ while (rs.next()){ // Stuff... { } finally{ rs.close(); }} catch(SQLException e){ // Logging...} finally{ try{ stmt.close(); } catch(SQLException whoTheFuckCares){ }; } Really, how many other ways are there to do it I wonder now? (Apart from wrapping certain things, like the last try-catch clause in some general purpose closer util?). /Casper --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
I still kind-of like listening to Joel and Jeff. Both make me cringe at times, but I like their attitude towards product design and I think Joel has quite some insight into the marketing/business side of software. But I don't think I'd want either as the chief architect of some enterprise software :-) Peter Casper Bang wrote: I lost my respect for Joel a while ago - he comes at you in very bold, definitive and authoritative fashion (especially on StackOverflow where he's down right annoying). Exceptions cater well to OO, you can centralize error handling and dispatching via polymorphism as well as associate whatever context that's needed. I don't think (hope) many in here wants to go back to interpreting return values. /Casper On 20 Aug., 16:03, Martin Wildam mwil...@gmail.com wrote: Anyone a fan of this:http://www.joelonsoftware.com/items/2003/10/13.html I am. :-) --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Number one clearly does not apply to checked exceptions, number two applies to returning values, too. Of course you could assign a value and follow the approach of having a single return statement at the end, but I never understood why the resulting code should be any easier. Peter Martin Wildam wrote: Anyone a fan of this: http://www.joelonsoftware.com/items/2003/10/13.html I am. :-) --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
As I said: in cases where you want to have a version of your code where the exception bubbles up and one where it doesn't you'll get the duplication. I think that is usually a bad idea, although I must admit the wrapper case you describe is an exception since the layer is the same. I don't see that problem spread too far, though. If your code is really that big, I'd even consider this: public class UnsafeWrapper implements UnsafeInterface { protected UnsafeInterface orig; ... public doAction() throws Ex { ... orig.doAction(); } } public class SafeWrapper implements SafeInterface { ... public doAction() { ... try { orig.doAction(); // call on UnsafeWrapper.doAction() } catch(Ex e) { // won't happen } } } Not very elegant, but avoids major duplication. I believe that with union types the whole problem would disappear since the subtyping would allow using generics to create the different versions. As long as exceptions are not part of the type signature it won't happen in Java. Peter Reinier Zwitserloot wrote: Peter, I still don't see how that'll avoid code duplication. Let's say, for argument's sake, that a FilterInputStream's read() method contains 4 pages of complex code. This code calls back into the filtered stream's read method loads of times. How would we avoid duplicating these 4 pages if we want 2 types of FilterInputStream: One that wraps a Safe InputStream and does not throw IOException, and one that wraps an unsafe InputStream and does throw IOException. On Aug 20, 9:36 am, Peter Becker peter.becker...@gmail.com wrote: Here you go (three files): = test/Unsafe.java== package test; import java.io.IOException; public interface Unsafe { void method() throws IOException; } = test/Safe.java == package test; public interface Safe extends Unsafe { void method(); } =test/Test.java=== package test; import java.io.IOException; public class Test { class UnsafeImpl implements Unsafe { @Override public void method() throws IOException { throw new IOException(); // ok } }; class SafeImpl implements Safe { @Override public void method() { // can't throw here } }; void method1(Unsafe unsafe) { unsafe.method(); // error, need to deal with exception } void method2(Safe safe) { safe.method(); // ok } } == The one trick is to realize that the safe version is actually the more specific one. If you think of the exception in terms of the type union (not accurate, but a decent analogy), then Unsafe.method() returns void|IOException while Safe.method() returns void, which is a more specific type, thus the return types are co-variant. More generally you can argue that Safe.method() makes stronger guarantees about its behavior than Unsafe.method(), so subtyping is legal. Apart from the one marked position the code above is legal Java. Peter Reinier Zwitserloot wrote: On Aug 20, 12:21 am, Peter Becker peter.becker...@gmail.com wrote: No implementation would be duplicated, the safe version could be a subtype of the unsafe one. Not too many interfaces will face that problem. To me it seems much better than not distinguishing. Can you show me how this would work? I have a hard time seeing how you can do that without (oh, the irony), employing some sort of sneakythrow mechanism. I guess we will have to agree to disagree here, but I'm fairly sure the idealism lost in allowing sneakythrow is minor, whereas the amount of pain you can solve is sizable. (in practice, due to widespread bad API design we all know will never ever get fixed, such as in the core JDK) --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
On Aug 21, 11:33 am, Peter Becker peter.becker...@gmail.com wrote: Number one clearly does not apply to checked exceptions, number two applies to returning values, too. Of course you could assign a value and follow the approach of having a single return statement at the end, but I never understood why the resulting code should be any easier. Both, They are invisible in the source code. and They create too many possible exit points target the hidden jumps in code. While debugging Java code with heavy use of exceptions I found out plenty of possibilities in code where some code lines were or were not executed depending on the exceptions occurring. In reality I would need to write plenty of nested finally blocks to ensure correct handling of all steps. Let me draw a constructed extreme opposite example not using exceptions (before you comment on this example, know that I already understood that this is no good practice): boolean goAhead = true; if (!checkEdits()) goAhead = false; if (!checkConfig()) goAhead = false; if (!openDestinationFile()) goAhead = false; //Prechecks failed so we leave if (!goAhead) return goAhead; //Start with regular work if (goAhead) { //We do some first transaction startTransaction(); doSomeSaveWorkThatCannotFail(); if (!doSomeTransactionWork()) goAhead = false; } if (goAhead) { doSomeMoreSaveWorkThatCannotFail(); yetAnotherBunchOfOperations(); if (!saveSomeDataOrDoSomethingElse()) goAhead = false; } if (goAhead) commitTransaction(); else rollBackTransaction(); The difference here is that you have no ACCIDENTALLY LINE SKIPPING. If you use instead something like this: try { checkEdits(); checkConfig(); openDestinationFile(); } catch (Exception e) { throw new PreCheckException(); } try { startTransaction(); doSomeSaveWorkThatCannotFail(); doSomeTransactionWork(); doSomeMoreSaveWorkThatCannotFail(); yetAnotherBunchOfOperations(); saveSomeDataOrDoSomethingElse(); commitTransaction(); } catch (SomeBusinessLogicException e) { //Where did I get my Exception from? Until which line the above has been processed? rollBackTransaction(); } catch (SomeTransactionException e) { //Where did I get my Exception from? Until which line the above has been processed? rollBackTransaction(); } catch (IOException e) { //Again we need the rollback rollBackTransaction(); } For the first part it makes no big difference - a little less work with using exceptions. In the second part you can't easily see (without examing javadoc of the called methods) which lines could have produced the exception. Encapsulating every single operation with try-catch is clearly not an option as it produces much more boilerplate (if several lines could throw the same exceptions) than using return codes. An advantage of using return codes is having a clear information about the overall status of the whole operation automatically. BUT: I think the handling of the different exceptions can be solved with throwing your own Exception type instead of returning a resultCode. And I think to remember something like this recommended by Josh Bloch in his book Effective Java (just don't remember which item and I don't have the book at hand). The only thing is the need of an extra Class for your application exception(s). Hey, and you can throw an exception that contains either a return code - there you would have everything. - Remaining issue is only that in some cases I simply don't care of the return codes and I can decide this in the parent method. But this can be solved using Unchecked Exceptions instead of checked exceptions. - And this is the point where I love to have the option of using checked or unchecked exceptions. Thank you guys - with your help I got cleared that up. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
I can follow your argument to some extent, but wouldn't the equivalent, exception-based code have a try/catch block per if(goAhead)? I agree that this would create code that is more verbose, but otherwise it seems equivalent. I take the point that it is possible to make code harder to read using exceptions in a way that is not possible without. I must admit I didn't really think it through when I read Joel's blog post. There is the opposite danger, though: ignoring a return value. Since C-like languages allow functions to be called as statements, it is pretty easy to just ignore the fact that there is an error code returned. Checked exceptions force you to deal with the issue. Of course that problem could also be fixed by disallowing calling functions as statements, which I think would be a good idea not just for this reason. Peter Martin Wildam wrote: On Aug 21, 11:33 am, Peter Becker peter.becker...@gmail.com wrote: Number one clearly does not apply to checked exceptions, number two applies to returning values, too. Of course you could assign a value and follow the approach of having a single return statement at the end, but I never understood why the resulting code should be any easier. Both, They are invisible in the source code. and They create too many possible exit points target the hidden jumps in code. While debugging Java code with heavy use of exceptions I found out plenty of possibilities in code where some code lines were or were not executed depending on the exceptions occurring. In reality I would need to write plenty of nested finally blocks to ensure correct handling of all steps. Let me draw a constructed extreme opposite example not using exceptions (before you comment on this example, know that I already understood that this is no good practice): boolean goAhead = true; if (!checkEdits()) goAhead = false; if (!checkConfig()) goAhead = false; if (!openDestinationFile()) goAhead = false; //Prechecks failed so we leave if (!goAhead) return goAhead; //Start with regular work if (goAhead) { //We do some first transaction startTransaction(); doSomeSaveWorkThatCannotFail(); if (!doSomeTransactionWork()) goAhead = false; } if (goAhead) { doSomeMoreSaveWorkThatCannotFail(); yetAnotherBunchOfOperations(); if (!saveSomeDataOrDoSomethingElse()) goAhead = false; } if (goAhead) commitTransaction(); else rollBackTransaction(); The difference here is that you have no ACCIDENTALLY LINE SKIPPING. If you use instead something like this: try { checkEdits(); checkConfig(); openDestinationFile(); } catch (Exception e) { throw new PreCheckException(); } try { startTransaction(); doSomeSaveWorkThatCannotFail(); doSomeTransactionWork(); doSomeMoreSaveWorkThatCannotFail(); yetAnotherBunchOfOperations(); saveSomeDataOrDoSomethingElse(); commitTransaction(); } catch (SomeBusinessLogicException e) { //Where did I get my Exception from? Until which line the above has been processed? rollBackTransaction(); } catch (SomeTransactionException e) { //Where did I get my Exception from? Until which line the above has been processed? rollBackTransaction(); } catch (IOException e) { //Again we need the rollback rollBackTransaction(); } For the first part it makes no big difference - a little less work with using exceptions. In the second part you can't easily see (without examing javadoc of the called methods) which lines could have produced the exception. Encapsulating every single operation with try-catch is clearly not an option as it produces much more boilerplate (if several lines could throw the same exceptions) than using return codes. An advantage of using return codes is having a clear information about the overall status of the whole operation automatically. BUT: I think the handling of the different exceptions can be solved with throwing your own Exception type instead of returning a resultCode. And I think to remember something like this recommended by Josh Bloch in his book Effective Java (just don't remember which item and I don't have the book at hand). The only thing is the need of an extra Class for your application exception(s). Hey, and you can throw an exception that contains either a return code - there you would have everything. - Remaining issue is only that in some cases I simply don't care of the return codes and I can decide this in the parent method. But this can be solved using Unchecked Exceptions instead of checked exceptions. - And this is the point where I love to have the option of using checked or unchecked exceptions. Thank you guys - with your help I got cleared that up. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email
[The Java Posse] Re: How do YOU handle Exceptions?
I take the point that it is possible to make code harder to read using exceptions in a way that is not possible without. I must admit I didn't really think it through when I read Joel's blog post. Joel seems to think of exceptions as mere alternative return points and in that goto light, he has a point. However exceptions are meant to be used for exceptional cases and not a replacement for proper factored condition checking down the primary path. Another problem with Joel's view is that of context, if you can only signal an error code, you'll have to resort to some shared/mutable place for further context. There is the opposite danger, though: ignoring a return value. Since C-like languages allow functions to be called as statements, it is pretty easy to just ignore the fact that there is an error code returned. Checked exceptions force you to deal with the issue. Well they force you to acknowledge them, but they don't really do anything else and as such can provide a false sense of security (can be swallowed or logged). At least with a non-checked, an unhandled problem would just bubble up to the surface and be trapped in some high-level place around the message pump. /Casper --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
On 21 Aug., 15:50, Martin Wildam mwil...@gmail.com wrote: I think the problem of context you also have when dealing with an exception on the low level. Context is known most likely only by some parent caller but on the other hand the parent caller often does not have any clue about how some functionality has been implemented on the low level and hence either does not really know what happens. Oh with context, I was more thinking about supplying additional information from down below where the exception got thrown. Think of an input field of a some complex UI, say an IDE's property editor. If you supply invalid input, the component's model (or observers of it) can raise a PropertyVetoException and supply the original PropertyChangeEvent as a member. When you catch this PropertyVetoException higher up, you can use the PropertyChangeEvent member to see which property you're dealing with, what the value was originally and what the user tried to enter. So you show an error dialog with this information as well as pointing out constraints of the particular input in question. Conceptually, you pass new context backwards on the existing call stack. This can be abused of course, primarily concern being leaking abstractions. However it beats having to deal with a tangled decentralized web of conditionals and shared variables to get to the same context. /Casper --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
On Aug 21, 2:07 pm, Peter Becker peter.becker...@gmail.com wrote: I take the point that it is possible to make code harder to read using exceptions in a way that is not possible without. I must admit I didn't really think it through when I read Joel's blog post. I think the reduced readability is the core disadvantage of using Exceptions. And I think that it is easier to create buggy code with exceptions - especially for beginners. (I know that most of those doing Java do it since a long while but they get older and junger people must somehow follow them). There is the opposite danger, though: ignoring a return value. Since C-like languages allow functions to be called as statements, it is pretty easy to just ignore the fact that there is an error code returned. Checked exceptions force you to deal with the issue. Whether it is an exception or a return code you always can drop it or deal with it. When I use a method like openFile or something the first thing automatically is to look for a return code. Of course that problem could also be fixed by disallowing calling functions as statements, which I think would be a good idea not just for this reason. I would loose then the option to ignore the result which may make sense (e.g. loading an optional configuration file). People want closures, annotations and all the like but then I should get limited how to use a simple method? Best regards, Martin. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Hi Possefolks, I've been following both of the Exception-handling mega-threads and have some opinions too, though unlikely original given the length of the thread. Checked exceptions *are* a failed experiment. I thought they were a good idea when I first ran into them, but the reality is quite different. In practice they cause details of the implementation to leak into the method signatures. The way to avoid that is, of course, to provide exceptions of the correct abstraction level at each module boundary and wrap, wrap, wrap. Welcome, stacktrace-from-hell. Some have argued that there's nothing wrong with checked exceptions, per se, it's just that people don't use them right. This is akin to acknowledging that every attempt to practice communism on a national level has lead to a repressive police state, and yet still insisting that it would be a great way to run a country, if only people would do it right! A good idea that can only be implemented badly, isn't a good idea. Joel's article, I can't really agree with, though it's a pretty old post. Exceptions as an alternate form a control flow have their place. I've seen the sorts of contortions they go through in the Subversion code base (ANSI-C) to do error handling. Basically they've co-opted the normal function return for exception handling. APIs all return some kind of svn_error_t structure. It's a solution that's positively screaming for an exception mechanism. And yet... I don't think this would have helped them much since in a language without automatic resource management the sort of unstructured control flow exceptions bring must really be hell. I wish Java had a good way of dealing with partial functions (i.e. functions that can't return a sensible value for all possible inputs). The only options we seem to have are: throw an exception or return null. Java's null is a mess. (Though sometimes the Null Object Pattern can help here.) Languages with a Maybe type (e.g. Scala) are appealing. In my more perverse moments, I imagine exceptions seem a little like INTERCAL's COMEFROM statement. // Ben --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Martin Wildam wrote: On Aug 21, 2:07 pm, Peter Becker peter.becker...@gmail.com wrote: I take the point that it is possible to make code harder to read using exceptions in a way that is not possible without. I must admit I didn't really think it through when I read Joel's blog post. I think the reduced readability is the core disadvantage of using Exceptions. And I think that it is easier to create buggy code with exceptions - especially for beginners. (I know that most of those doing Java do it since a long while but they get older and junger people must somehow follow them). In my experience beginners hardly ever think of the exceptional cases to begin with ;-) The reduced readability is IMO not really applicable either, since I don't see many beginners writing complex code in a neat fashion like your example. And an experienced Java programmer shouldn't write the big bit of code where the exception just bubbles out. There is the opposite danger, though: ignoring a return value. Since C-like languages allow functions to be called as statements, it is pretty easy to just ignore the fact that there is an error code returned. Checked exceptions force you to deal with the issue. Whether it is an exception or a return code you always can drop it or deal with it. When I use a method like openFile or something the first thing automatically is to look for a return code. But is that true for your average Joe Java? Of course that problem could also be fixed by disallowing calling functions as statements, which I think would be a good idea not just for this reason. I would loose then the option to ignore the result which may make sense (e.g. loading an optional configuration file). People want closures, annotations and all the like but then I should get limited how to use a simple method? Anything that has a return value that can be ignored seems suspicious to me. Arguably in Javaland you couldn't enforce such rule without some option of ignoring it in places, but I'd quite like at least a compiler warning with matching @SuppressWarning. For me an ideal system would have functions that are SEF and procedures that never return anything. But I'm a bit of a purist sometimes. Peter --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
B Smith-Mannschott wrote: [...] Some have argued that there's nothing wrong with checked exceptions, per se, it's just that people don't use them right. This is akin to acknowledging that every attempt to practice communism on a national level has lead to a repressive police state, and yet still insisting that it would be a great way to run a country, if only people would do it right! A good idea that can only be implemented badly, isn't a good idea. The point I'm trying to make is that many people come to that conclusion after one failed experiment. Not very scientific, particularly since that experiment was executed pretty badly IMO. While I'm still arguing for checked exceptions, I'm not 100% convinced their good yet either. But nearly every argument I see why they are bad is about how they are used badly, with the conclusion of some intrinsic badness. This is highly illogical, my personal conclusion is we need more experiments. Or some arguments why they are intrinsically bad. Martin's recent argument about the confusing flow wasn't too bad, but interestingly applies to all exceptions, not just the checked flavor. Peter --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
The one trick is to realize that the safe version is actually the more specific one. If you think of the exception in terms of the type union (not accurate, but a decent analogy), then Unsafe.method() returns void|IOException while Safe.method() returns void, which is a more specific type, thus the return types are co-variant. I think Reinier was refering to this: x.doSomething(new StringReader(xyz)); x.doSomething(someUnsafeReader()); Unless you have two overloads of doSomething both invocations will throw an IOException. Having two overloads is code duplication though. Even if it looks like that: public void doSomething(SafeReader r) { try { doSomething((UnsafeReader)r); } catch(IOException e) { throw new RuntimeException(e); } } With kind regards Ben --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
On 19 Aug., 20:45, Reinier Zwitserloot reini...@gmail.com wrote: disjoint types are structural in that you weaken the namespacing of members. Members are only namespaced by virtue of their container. So lets say I do this (I apologize in advance for the cliché factor of this example): public class com.ren.Gun { public void shoot() { System.out.println(BANG!); } } public class com.stimpy.Camera { public void shoot() { System.out.println(Smile!); } } public void pointAndClick(Gun | Camera object) { object.shoot(); } should that be legal code? I'd argue no - the fact that both Gun and Camera have a 'shoot' method is a pure coincidence. I don't think that argument works here. Yeah, idiots will be idiots, but it would take an extraordinary idiot to call shoot() on an object of type Gun|Camera. Why do you insist on having more slack in your type system, just to exclude a tiny class of errors that noone is going to make anyways? With kind regards Ben --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Ben Schulz wrote: The one trick is to realize that the safe version is actually the more specific one. If you think of the exception in terms of the type union (not accurate, but a decent analogy), then Unsafe.method() returns void|IOException while Safe.method() returns void, which is a more specific type, thus the return types are co-variant. I think Reinier was refering to this: x.doSomething(new StringReader(xyz)); x.doSomething(someUnsafeReader()); Unless you have two overloads of doSomething both invocations will throw an IOException. Having two overloads is code duplication though. Even if it looks like that: public void doSomething(SafeReader r) { try { doSomething((UnsafeReader)r); } catch(IOException e) { throw new RuntimeException(e); } } Here's my version of the story: If you are happy to deal with the exception, then just write the version for the UnsafeReader which will take SafeReader implementations. If you don't want to allow the exceptions, write the SafeReader version only. If you feel the need to pass the exceptions through without dealing with them (not even wrapping them into an exception suitable for your layer), then you are probably creating a leaky abstraction. But I agree that this pattern could not easily be retrofitted into the JDK or other code. Peter --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Joel on Software's view that exceptions are bad and you should be using archaic C style error codes is, in a word: Effing Retarded. Follow his advice at your own peril. On Aug 20, 4:03 pm, Martin Wildam mwil...@gmail.com wrote: Anyone a fan of this:http://www.joelonsoftware.com/items/2003/10/13.html I am. :-) --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Anyone a fan of this: http://www.joelonsoftware.com/items/2003/10/13.html I am. :-) --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
I lost my respect for Joel a while ago - he comes at you in very bold, definitive and authoritative fashion (especially on StackOverflow where he's down right annoying). Exceptions cater well to OO, you can centralize error handling and dispatching via polymorphism as well as associate whatever context that's needed. I don't think (hope) many in here wants to go back to interpreting return values. /Casper On 20 Aug., 16:03, Martin Wildam mwil...@gmail.com wrote: Anyone a fan of this:http://www.joelonsoftware.com/items/2003/10/13.html I am. :-) --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
On Aug 20, 4:13 pm, Casper Bang casper.b...@gmail.com wrote: Exceptions cater well to OO, you can centralize error handling and dispatching via polymorphism as well as associate whatever context that's needed. I don't think (hope) many in here wants to go back to interpreting return values. I don't know Joel personally but when dealing with exceptions for a while I found by accident his opinion on Exceptions and I felt so happy not being the only one not using exceptions all the time. - I personally also use exceptions but for some very common methods that are definitely useful in definitely very different cases it really makes sense coming back to return values. - At least not only from my point of view. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Peter, I still don't see how that'll avoid code duplication. Let's say, for argument's sake, that a FilterInputStream's read() method contains 4 pages of complex code. This code calls back into the filtered stream's read method loads of times. How would we avoid duplicating these 4 pages if we want 2 types of FilterInputStream: One that wraps a Safe InputStream and does not throw IOException, and one that wraps an unsafe InputStream and does throw IOException. On Aug 20, 9:36 am, Peter Becker peter.becker...@gmail.com wrote: Here you go (three files): = test/Unsafe.java== package test; import java.io.IOException; public interface Unsafe { void method() throws IOException; } = test/Safe.java == package test; public interface Safe extends Unsafe { void method(); } =test/Test.java=== package test; import java.io.IOException; public class Test { class UnsafeImpl implements Unsafe { @Override public void method() throws IOException { throw new IOException(); // ok } }; class SafeImpl implements Safe { @Override public void method() { // can't throw here } }; void method1(Unsafe unsafe) { unsafe.method(); // error, need to deal with exception } void method2(Safe safe) { safe.method(); // ok } } == The one trick is to realize that the safe version is actually the more specific one. If you think of the exception in terms of the type union (not accurate, but a decent analogy), then Unsafe.method() returns void|IOException while Safe.method() returns void, which is a more specific type, thus the return types are co-variant. More generally you can argue that Safe.method() makes stronger guarantees about its behavior than Unsafe.method(), so subtyping is legal. Apart from the one marked position the code above is legal Java. Peter Reinier Zwitserloot wrote: On Aug 20, 12:21 am, Peter Becker peter.becker...@gmail.com wrote: No implementation would be duplicated, the safe version could be a subtype of the unsafe one. Not too many interfaces will face that problem. To me it seems much better than not distinguishing. Can you show me how this would work? I have a hard time seeing how you can do that without (oh, the irony), employing some sort of sneakythrow mechanism. I guess we will have to agree to disagree here, but I'm fairly sure the idealism lost in allowing sneakythrow is minor, whereas the amount of pain you can solve is sizable. (in practice, due to widespread bad API design we all know will never ever get fixed, such as in the core JDK) --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
On Wed, Aug 19, 2009 at 11:45 AM, Reinier Zwitserloot reini...@gmail.comwrote: disjoint types are structural in that you weaken the namespacing of members. Disjoint types aren't structural unless the language makes them so. Java could be extended with disjoint types that compute a least upper bound nominally rather than structurally. Or it could require type dispatch and never use a LUB. As for namespacing, well it can't be made any weaker than it already is. It's a weak concept and always has been. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Exactly. The Camera/Gun argument against structural typing doesn't hold water because the programmer's error is exactly the same semantic problem as // my library interface Camera { void shoot(); } // somebody else's code class Bazooka extends Camera {...} The only constraints that Java can enforce on implementing the Camera interface are structural, it knows nothing about our domain. In this particular case the mistake seems silly because of our intuition that Bazookas aren't Cameras. But Java also allows us to say // my library // this interface is for things that shoot non-destructively like still cameras, video cameras, and sextants. interface Shootable { void shoot(); } Now writing class Bazooka extends Shootable {...} violates the library's constraint, but the constraint is in documentation that is easily missed by a programmer. In this toy domain that seems contrived, but real world examples abound where classes implement the structural requirements of an interface but don't follow the additional requirements in the documentation. On Thu, Aug 20, 2009 at 2:26 AM, Ben Schulz ya...@gmx.net wrote: should that be legal code? I'd argue no - the fact that both Gun and Camera have a 'shoot' method is a pure coincidence. I don't think that argument works here. Yeah, idiots will be idiots, but it would take an extraordinary idiot to call shoot() on an object of type Gun|Camera. Why do you insist on having more slack in your type system, just to exclude a tiny class of errors that noone is going to make anyways? With kind regards Ben --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
well put :) On Aug 20, 8:36 am, Reinier Zwitserloot reini...@gmail.com wrote: Joel on Software's view that exceptions are bad and you should be using archaic C style error codes is, in a word: Effing Retarded. Follow his advice at your own peril. On Aug 20, 4:03 pm, Martin Wildam mwil...@gmail.com wrote: Anyone a fan of this:http://www.joelonsoftware.com/items/2003/10/13.html I am. :-) --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
This thread inspired me. Thanks in particular to Casper. Here you go, an annotation processor that removes the notion of checked exceptions completely from your javac: http://groups.google.com/group/javaposse/browse_thread/thread/26ec00e0601023d On Aug 21, 12:00 am, phil swenson phil.swen...@gmail.com wrote: well put :) On Aug 20, 8:36 am, Reinier Zwitserloot reini...@gmail.com wrote: Joel on Software's view that exceptions are bad and you should be using archaic C style error codes is, in a word: Effing Retarded. Follow his advice at your own peril. On Aug 20, 4:03 pm, Martin Wildam mwil...@gmail.com wrote: Anyone a fan of this:http://www.joelonsoftware.com/items/2003/10/13.html I am. :-) --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
I'd much rather have a closure proposal where a method that takes a closure that has tennant's correspondence principle is strictly enforced by the compiler to keep the closure stack-safe. In other words, legal operations are: 1. Running the closure, 2. Grabbing info off of the closure object (running its toString or some such) 3. passing it on to another method that accepts closures. Wouldn't you lose the ability to parallelize? I might want to find an element in a collection that satisfies a certain predicate. The first thread to find one gets to return its findings, the others are ignored. With kind regards Ben --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Interestingly Java's generics allow the dual construction on interfaces: public T extends Interface1 Interface2 void someMethod(T param) {...} I really like the idea of having the anonymous unions/joins and considering that the resulting type system should be a complete lattice they sound manageable to me -- both for the compiler and the human reader. Does anyone know reasons why no language seems to have this feature? Peter James Iry wrote: On Tue, Aug 18, 2009 at 3:13 AM, Peter Becker peter.becker.de http://peter.becker.de@gmail.com http://gmail.com wrote: What I would really like to see is a meet/or/disjunction/union operator in the type system, with a case-like construct to resolve the resulting types. Scala has two things that are halfway there (Either, case classes), but neither is the full monty. Few type systems have true union types. The algebraic data types of the ML and Haskell families, for instance, do not allow unioning of types without explicitly creating a new type with its own constructors. See Either which in Haskell looks like. data Either a b = Left a | Right b In Scala, Haskell, or SML Either is really just a way of faking union typing in a type system that doesn't do union typing. Java is actually very unusual in that the small bit of its type system devoted to exceptions basically has union types. If a method says it throws A,B,C then the union A,B,C forms a type and the type A,B is a subtype, the type A,B,C,D is a supertype. With regards to declared exceptions on methods Java is covariant. I know that's not how checked exceptions are normally presented, but that's how the type rules work. But then Java, as usual, isn't very regular about this union typing business. You can write Integer myFunction(File file) throws IOException, MyBusinessException {...} But if you try to make it first class with something like interface FunctionIn, Out, Exc { Out apply(In in) throws Exc; } You can't then write something like new FunctionFile, Integer, {IOException, MyBusinessException} {...} Your first class function has to pick one exception or declare that it throws a common supertype. Project Coin proposed the ability to catch mutliple exception types with one catch block. That can be seen as extending union typing just a touch further, but it still doesn't cover exception types as type parameters. It's not surprising to me at all that Java remains virtually the only language with checked exceptions. They might be a fine idea, but making them usable and consistent across the language is very tough business. Checked exceptions are what's called an effects system, which is a way to extend a type system so that functions describe effects they might have beyond computing a value. Creating an effects system that is usable and consistent across the language is very much ongoing research. See Disciple http://www.haskell.org/haskellwiki/DDC/EffectSystem, but I warn you it's not for the faint of heart. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
So there IS a bug for that. I've added a link to http://bugs.sun.com/view_bug.do?bug_id=6534270 to the documentation for lombok's @SupressWarnings, which does the exact same thing. Christian: If you go in with a class file editor and remove the throws clauses, the code will continue to run just fine. The validator will NOT choke on it. I'm sure of that bit, and I'm almost sure that you may catch a checked exception that no statement in the try block could possibly throw, as well. javac won't compile such code, but again that's just javac, and not a JVM thing. On Aug 19, 3:06 am, Alex Buckley alex.buck...@sun.com wrote: I'm slightly embarrassed to admit I'm a fan ofhttp://bugs.sun.com/view_bug.do?bug_id=6534270 On Aug 15, 5:56 am, Jeff Grigg jeffgr...@charter.net wrote: I like the beauty and simplicity of completely empty catch blocks. ;- OK, some developers, to comply with corporate documentation standards, put comments there. ;- (Reality is that I'll usually wrap checked exceptions in RuntimeExceptions at a low level, and then catch Exception at the top level -- to log it and abort or retry the transaction or user action. There's a lot of really bad code out there that misuses exceptions and does exception handling cleanup wrong. It's a problem!!) --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
I really like the idea of having the anonymous unions/joins and considering that the resulting type system should be a complete lattice they sound manageable to me -- both for the compiler and the human reader. Does anyone know reasons why no language seems to have this feature? I'm not much of a PLTist, but I'm guessing the reason uions don't make it into general purpose, object oriented languages is that they're inherently structural. Just a guess though. (The alternative is having to check the runtime type and downcast, which pretty much defeats the purpose.) With kind regards Ben --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
I can confirm this is practice, in fact, the modification to Check.java I described a few posts ago would also allow compilation of code with catch clauses of checked exceptions not really being thrown. /Casper On 19 Aug., 13:14, Reinier Zwitserloot reini...@gmail.com wrote: So there IS a bug for that. I've added a link tohttp://bugs.sun.com/view_bug.do?bug_id=6534270to the documentation for lombok's @SupressWarnings, which does the exact same thing. Christian: If you go in with a class file editor and remove the throws clauses, the code will continue to run just fine. The validator will NOT choke on it. I'm sure of that bit, and I'm almost sure that you may catch a checked exception that no statement in the try block could possibly throw, as well. javac won't compile such code, but again that's just javac, and not a JVM thing. On Aug 19, 3:06 am, Alex Buckley alex.buck...@sun.com wrote: I'm slightly embarrassed to admit I'm a fan ofhttp://bugs.sun.com/view_bug.do?bug_id=6534270 On Aug 15, 5:56 am, Jeff Grigg jeffgr...@charter.net wrote: I like the beauty and simplicity of completely empty catch blocks. ;- OK, some developers, to comply with corporate documentation standards, put comments there. ;- (Reality is that I'll usually wrap checked exceptions in RuntimeExceptions at a low level, and then catch Exception at the top level -- to log it and abort or retry the transaction or user action. There's a lot of really bad code out there that misuses exceptions and does exception handling cleanup wrong. It's a problem!!) --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Yes, it would lose you the ability to parallelize. There may be a way out of this: Have the following system call: public class System { public static R R unsafe(do R closure) { return closure; } } The above code would not compile (you may not let a 'do' parameter escape, but the method is hardcoded into the class library so that it does in fact compile. You can now remove the 'you may not let your closure escape' clause, at your own peril, by unlinking it like so: Runnable youCanStoreMeNow = unsafe(parameter); The unsafe method would explain in the javadoc that you need to take on ALL RESPONSIBILITY to transport any long effects back to the originating thread. So, you need to transport any and all exceptions that fall out of youCanStoreMeNow back to the originating thread, and the same goes for the throwables that are used to implement long break/ return/continue (see the BGGA proposal for more details on those). This is clearly 'here be dragons' territory, but how often exactly does one write a library for parallelizing things? Maybe like 5 times in the entire world? Doesn't everyone else just use forkjoin? So, I'm perfectly allright with having the type system be no help whatsoever to you in the exceedingly rare circumstance when the rocket scientists go write this function. On Aug 19, 8:58 am, Ben Schulz ya...@gmx.net wrote: I'd much rather have a closure proposal where a method that takes a closure that has tennant's correspondence principle is strictly enforced by the compiler to keep the closure stack-safe. In other words, legal operations are: 1. Running the closure, 2. Grabbing info off of the closure object (running its toString or some such) 3. passing it on to another method that accepts closures. Wouldn't you lose the ability to parallelize? I might want to find an element in a collection that satisfies a certain predicate. The first thread to find one gets to return its findings, the others are ignored. With kind regards Ben --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Replies inline. The problem is simply this: You think I was trying to argue against checked exceptions in general. I wasn't. I was arguing that the checked exception system isn't perfect, and therefore programmers need to be given a tool to say to the compiler: I know better than you. Stop whining. More specific arguments follow below, inline. On Aug 19, 12:56 am, Peter Becker peter.becker...@gmail.com wrote: Runnable does not let you throw Exceptions. Anyone up for defending this grievous API design? The amount of annoyance that this is caused me is almost limitless. Where would that exception go? The same place the RuntimeExceptions thrown by the runnable go. Your argument only makes sense if Runnable was precluded from throwing -any and all- exceptions. That's not true. What possible use is there for someone invoking a Runnable (which after all stands for: I have no idea what this does, other than run... something...) - to differentiate between checked exceptions and unchecked exceptions? The thing threw an exception. It doesn't matter what kind of exception was thrown. So, for Thread, that would be: The exception handler of that thread. It makes some sense to me. The servlet container cares only about the fact that the servlet failed, the question why is rather secondary on that level. You could also imagine that subtypes are used to distinguish the actual problem. Sure, and if ServletException had a mechanism to specify certain extra info (such as which error code and message to return), that would be great stuff. But either way, a servlet container MUST handle *ANY* exception falling out of a servlet (sneakyThrow, scala, jruby, jython, any other non-java language on the VM, and mixing class files from different compile runs can ALL result in a method throwing a checked exception it didn't declare, so you already have to handle them!) If you just allow any exception to go through (e.g. by letting the methods throw Exception on the API level), programmers will forget to handle things they could handle. Idiots write idiot code. But, okay, I'll roll with your argument: Then why isn't there a mechanism to escape it? Why can't I say: Nono, compiler, I did not forget anything, this is what I want. Shut your yap. You're not really going to argue with me that there is no inconvenience at all here, right? InputStream.close() throws IOException. Nuff said. That only proves that exceptions are used badly in the JDK. That only proves? The JDK abuses checked exceptions - That's a pretty big deal! That's the whole point! That's why the language needs an escaping mechanism. The further damage caused by bad coders abusing the escaping mechanism are, in my opinion, much, __much__ smaller than the potential further damage that would no longer becaused because the mechanism is available. The occasional explicitly supressed checked exception that should have been handled is far less of a crime than code littered with this abomination: try { something(); } catch ( IOException e ) { e.printStackTrace(); //TODO Eclipse auto-generated this. The programmer never looked at it again, logging to system.err is just about the worst thing you could do here, and the original programmer only hit quickfix-add try catch block because he couldn't throw it onwards because he's implementing a servlet, or a runnable. } Sure, an idiot coded that. But we're all idiots some of the time, and you yourself put 'idiots exist' on the table as a legal line of reasoning. FilterInputStream and FilterOutputStream's methods throw IOException, but if I feed it a ByteArrayInputStream, or I let it filter into a ByteArrayOutputStream, then an IOException can never happen. Which could be solved by having safe and unsafe versions of the interface. Do you realize how much code duplication that would require? Exactly _BECAUSE_ you can't circumvent checked exception checking, you'd actually have to copy/paste every method. I cannot put into words the insanity of a system that would _require_ you to copy/paste vast tracts of code just to satisfy a system that is principally designed to help code maintainance. Talk about bass ackwards. In practice, you would most likely implement this by employing a sneaky throw hack. I can scarcely imagine a better case for enshrining sneaky throwing into the JLS, than this line of reasoning. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Jess, I think you misunderstand my closure proposal. It *DOES* have exception transparency. That's in fact exactly what it has. You further claim that you can't add exception transparency to Collections.sort() without making a change to the API. This isn't true! Read my post again - in my proposal, Collections.sort can be retrofitted with full migration and backwards compatibility to support exception transparency. On Aug 19, 3:58 am, Jess Holle je...@ptc.com wrote: Reinier Zwitserloot wrote: BGGA's checked exception handling is extremely complex. I don't like it at all. You can gripe about that, but it is the only thing that really makes a code block work normally. If you have something like: for ( ... ) { // some code that throw IOException } then you'd expect to have to catch IOException or declare throws IOException. If you don't have exception transparency, then when you use closures to do something like forEachWombat( ... ) { // do some stuff that throws IOException } You'd get totally different behavior -- which is *not* acceptable in my book. Exception transparency is complex in terms of implementation -- but rather simple in terms of usage. It's really a missing piece of Java generics and exception handling in Java as I see. As for Collections.sort() -- if you want this to allow throwing of checked exceptions from the Comparable then this is a dramatic change in the contract and, yes, Collections.sort() would have to be reimplemented. There's still a big different between public T foo() and public T foo() throws E -- the former is saying only serious unforeseen runtime exceptions could possibly occur in foo() -- that's the contract. That the Comparable contract and changing that is a big change. On the other hand, that's not to say that Callable wouldn't be a lot better as public T call() throws E than public T call() throws Exception. -- Jess Holle --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
I see this as an important change quite apart from the current debate. Catching an exception that cannot be thrown should be a *warning* not an error. I'm sick of having code stop compiling because someone stopped throwing a checked exception! That should *not* be a breaking change. There is justification for a warning -- something changed that you might want to look into and clean up accordingly -- but there's no cause for an error. This would be my #1 gripe about javac -- bar none. // Casper Bang wrote: I can confirm this is practice, in fact, the modification to Check.java I described a few posts ago would also allow compilation of code with catch clauses of checked exceptions not really being thrown. /Casper --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Catching an exception that cannot be thrown should be a *warning* not an error. I totally agree, talk about idiosyncrasies getting in the way of the job. Anyway, if someone wants to give it a try, grab this build of javac: http://82.103.135.236/javac.jar And notice there's no problem compiling something like this: public class CheckedExceptionTest{ public static void main(String... args){ Thread.sleep(100); // Throws InteruptedException (checked) try{ System.out.println(Dum da dum, inside try...); }catch(IOException e){ // Nothing throws IOException } } } /Casper --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
On Wed, Aug 19, 2009 at 1:03 AM, Peter Becker peter.becker...@gmail.comwrote: Interestingly Java's generics allow the dual construction on interfaces: public T extends Interface1 Interface2 void someMethod(T param) {...} Yeah, you can do intersection types in generics. But you can't write Interface1 Interface2 foo() {...} Interface1 Interface2 x = foo(); Also, note the syntax is different when you create a new type in that intersection class Bar implements Interface1, Interface2 Java is maddening with its irregularity. I really like the idea of having the anonymous unions/joins and considering that the resulting type system should be a complete lattice they sound manageable to me -- both for the compiler and the human reader. Does anyone know reasons why no language seems to have this feature? I honestly don't know. I'm not aware of any languages with that kind of union type. Certainly with Scala's pattern matching it would be a prime candidate for re-extracting union types, but even it doesn't have them. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
I may have mentioned it before, but due to very complex reasons I won't go into here, catching a checked exception that cannot be thrown will most likely become a warning and not an error in java 7. So, Jess, your #1 gripe may be about to be resolved*. *) As there isn't an umbrella JSR, let alone some sort of official list of java 7 changes, this isn't set in stone. It is, however, a likely requirement in order for a proposal on the coin shortlist that's been unanimously well accepted to be backwards compatible. We all know how anal sun gets about backwards compatibility, so for once you may keep your hopes up. On Aug 19, 1:58 pm, Jess Holle je...@ptc.com wrote: I see this as an important change quite apart from the current debate. Catching an exception that cannot be thrown should be a *warning* not an error. I'm sick of having code stop compiling because someone stopped throwing a checked exception! That should *not* be a breaking change. There is justification for a warning -- something changed that you might want to look into and clean up accordingly -- but there's no cause for an error. This would be my #1 gripe about javac -- bar none. // Casper Bang wrote: I can confirm this is practice, in fact, the modification to Check.java I described a few posts ago would also allow compilation of code with catch clauses of checked exceptions not really being thrown. /Casper --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
I don't follow. Union types don't seem particularly structural to me. They're the disjunction of other types, and if the other types are nominative then so is the union of them. A type like String | Integer contians all expressions that are Strings or Integers. The idea would be that you can write the followig. Here I'm borrowing a touch of Scala syntax to allow switch on runtime type and use | to indicate disjunction of types. void foo(String | Integer argument) { switch(argument) { case s : String = It was a String + s break; case i : Integer = It was an Integer + i } } The types of actual arguments would be checked statically. The type system would allow foo(hello) and foo(42) but would not allow foo(false). For backward compatibility, the argumenttype could be erased to the least upper bound (in this case Object) in the bytecode. Similarly, you could write String | Integer foo(Boolean flag) { if (flag) return 42; else return hello; } On Wed, Aug 19, 2009 at 4:21 AM, Ben Schulz ya...@gmx.net wrote: I'm not much of a PLTist, but I'm guessing the reason uions don't make it into general purpose, object oriented languages is that they're inherently structural. Just a guess though. (The alternative is having to check the runtime type and downcast, which pretty much defeats the purpose.) With kind regards Ben --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
That's what I was refering to as having to check the runtime type. I don't feel like you gained much in your sample, you could just replace String | Integer with Object and add a default: throw new AssertionError();. Obviously you gained type safety, but it would be much more useful if unions were structural: public static void closeSilently(InputStream|OutputStream|Reader| Writer|Channel preCloseable) { try { preCloseable.close(); } catch(IOException e) {} } With kind regards Ben On 19 Aug., 15:57, James Iry james...@gmail.com wrote: I don't follow. Union types don't seem particularly structural to me. They're the disjunction of other types, and if the other types are nominative then so is the union of them. A type like String | Integer contians all expressions that are Strings or Integers. The idea would be that you can write the followig. Here I'm borrowing a touch of Scala syntax to allow switch on runtime type and use | to indicate disjunction of types. void foo(String | Integer argument) { switch(argument) { case s : String = It was a String + s break; case i : Integer = It was an Integer + i } } The types of actual arguments would be checked statically. The type system would allow foo(hello) and foo(42) but would not allow foo(false). For backward compatibility, the argumenttype could be erased to the least upper bound (in this case Object) in the bytecode. Similarly, you could write String | Integer foo(Boolean flag) { if (flag) return 42; else return hello; } On Wed, Aug 19, 2009 at 4:21 AM, Ben Schulz ya...@gmx.net wrote: I'm not much of a PLTist, but I'm guessing the reason uions don't make it into general purpose, object oriented languages is that they're inherently structural. Just a guess though. (The alternative is having to check the runtime type and downcast, which pretty much defeats the purpose.) With kind regards Ben --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
On Wed, Aug 19, 2009 at 7:36 AM, Ben Schulz ya...@gmx.net wrote: don't feel like you gained much in your sample, you could just replace String | Integer with Object and add a default: throw new AssertionError();. Obviously you gained type safety, Isn't that kinda the point of a type system? :-) I've pushed the constraint that argument must be either an Integer or a String out of the documentation where only humans can get at it and into the type system where both humans and tools can understand it. but it would be much more useful if unions were structural: public static void closeSilently(InputStream|OutputStream|Reader| Writer|Channel preCloseable) { try { preCloseable.close(); } catch(IOException e) {} } Agreed, that would be more useful than only having type dispatch. But union types can join types that share virtually no common structure, so type dispatch is a must to make union typing useful while computing a common structural type is merely very nice for cutting down on code repetition. In a way you can see this stuff as generalizing what Java already does with checked exceptions and catch blocks. Several catch blocks in a series form a type dispatch mechanism. It would be nice if unions of exception types could be caught and dealt with using common code, but the exception system would be unusable if you couldn't dispatch on individual exception types. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Thanks for the info. That would be *great*. Reinier Zwitserloot wrote: I may have mentioned it before, but due to very complex reasons I won't go into here, catching a checked exception that cannot be thrown will most likely become a warning and not an error in java 7. So, Jess, your #1 gripe may be about to be resolved*. *) As there isn't an umbrella JSR, let alone some sort of official list of java 7 changes, this isn't set in stone. It is, however, a likely requirement in order for a proposal on the coin shortlist that's been unanimously well accepted to be backwards compatible. We all know how anal sun gets about backwards compatibility, so for once you may keep your hopes up. On Aug 19, 1:58 pm, Jess Holle je...@ptc.com wrote: I see this as an important change quite apart from the current debate. Catching an exception that cannot be thrown should be a *warning* not an error. I'm sick of having code stop compiling because someone stopped throwing a checked exception! That should *not* be a breaking change. There is justification for a warning -- something changed that you might want to look into and clean up accordingly -- but there's no cause for an error. This would be my #1 gripe about javac -- bar none. // Casper Bang wrote: I can confirm this is practice, in fact, the modification to Check.java I described a few posts ago would also allow compilation of code with catch clauses of checked exceptions not really being thrown. /Casper --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Obviously you gained type safety, Isn't that kinda the point of a type system? :-) I suppose, but for me it's more about why I should write down the types. If we asked Gilad Bracha, he'd probably say it's a bad idea because they restrain your thinking. Me, I say it's good because the compiler can verify that all messages sent are understood by their receivers. Structural unions would get me much farther in that direction and that's where I want to go. If I understand it correctly (and I can only hope in this case) I would not need to write down any types if higher-order unification was decidable. Wouldn't that be nice? With kind regards Ben --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
On Aug 18, 4:48 pm, Peter Becker peter.becker...@gmail.com wrote: phil swenson wrote: So you are saying it is better to quietly change behaviour than to make a change to an API that breaks source compatibility? I certainly would not agree to that. So every API written in every other language ever written in the history of software got it wrong eh? Exceptions mean something went wrong. You will detect this when it happens (testing, iterative dev). And again, it's almost always because of a bug or something else you can't gracefully handle (like server down as you mention). If you decide to handle one of these conditions, that's fine - but usually it's better to let the condition bubble up to the top thread an notify the user/email the admin. Sorry, but I call BS on that. SQLExceptions get thrown when the DB server is down or in trouble, when the network has issues and possibly other reasons that you do not encounter in test environments, so your testing won't help. Ok, I modify my original claim of it's almost always a bug to it's almost always a bug or a condition that you can't do anything about in code. If your db server is down, all you can do it manually intervene and get the thing running again. If you are in a scenario where data loss is unacceptable (where you would do a catch/retry), then you still need to handle runtime exceptions anyway. The key is to make the exception known and notify someone. Checked exceptions usually have the opposite effect. You can say that's because people don't use them correctly. Sure, but I still haven't seen anyone who does use them correctly. It's too much of a PITA. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Hi all, A few days ago I ran into an interesting article about Java Exceptions Handling on the Oracle technology website: http://www.oracle.com/technology/pub/articles/dev2arch/2006/11/effective-exceptions.html It covers checked/unchecked exceptions and multi-tier hints. Lorenzo --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Reinier Zwitserloot wrote: Replies inline. The problem is simply this: You think I was trying to argue against checked exceptions in general. I wasn't. I was arguing that the checked exception system isn't perfect, and therefore programmers need to be given a tool to say to the compiler: I know better than you. Stop whining. More specific arguments follow below, inline. On Aug 19, 12:56 am, Peter Becker peter.becker...@gmail.com wrote: Runnable does not let you throw Exceptions. Anyone up for defending this grievous API design? The amount of annoyance that this is caused me is almost limitless. Where would that exception go? The same place the RuntimeExceptions thrown by the runnable go. Your argument only makes sense if Runnable was precluded from throwing -any and all- exceptions. That's not true. What possible use is there for someone invoking a Runnable (which after all stands for: I have no idea what this does, other than run... something...) - to differentiate between checked exceptions and unchecked exceptions? The thing threw an exception. It doesn't matter what kind of exception was thrown. So, for Thread, that would be: The exception handler of that thread. Fair enough. I keep forgetting about runtime exceptions, that's why I like the checked ones :-) [...] If you just allow any exception to go through (e.g. by letting the methods throw Exception on the API level), programmers will forget to handle things they could handle. Idiots write idiot code. But, okay, I'll roll with your argument: Then why isn't there a mechanism to escape it? Why can't I say: Nono, compiler, I did not forget anything, this is what I want. Shut your yap. You're not really going to argue with me that there is no inconvenience at all here, right? The problem I see is that someone on a lower layer might have done this and the guy on the layer above is not aware of it. I know you will counter with the argument that the alternative is bad catches, and I agree to some extent. But those catches you describe (the e.printStackTrace() and similar) are known to be bad, adding a mechanism to the language makes it look much more legit. Of course the new RuntimeException(e) is much better, but I don't think it is a general solution either. InputStream.close() throws IOException. Nuff said. That only proves that exceptions are used badly in the JDK. That only proves? The JDK abuses checked exceptions - That's a pretty big deal! That's the whole point! That's why the language needs an escaping mechanism. It doesn't seem right to add language features to deal with crappy library design. The further damage caused by bad coders abusing the escaping mechanism are, in my opinion, much, __much__ smaller than the potential further damage that would no longer becaused because the mechanism is available. The occasional explicitly supressed checked exception that should have been handled is far less of a crime than code littered with this abomination: try { something(); } catch ( IOException e ) { e.printStackTrace(); //TODO Eclipse auto-generated this. The programmer never looked at it again, logging to system.err is just about the worst thing you could do here, and the original programmer only hit quickfix-add try catch block because he couldn't throw it onwards because he's implementing a servlet, or a runnable. } Sure, an idiot coded that. But we're all idiots some of the time, and you yourself put 'idiots exist' on the table as a legal line of reasoning. What you are proposing seems to me like making a mediocre solution easy to avoid people doing the really bad ones. Call me an idealist, but I don't really like that. Just think of the problem one layer above the one that may use the sneaky throws: you might get some methods you call that pass the IOException to you, some might do what I consider right and chain it with their own checked exception and other just do the sneaky throw. To figure out what's happening I really need to know the internals of each method down to the bottom. The alternative is catch(Exception). Admittedly the problem is already there since Java has both checked and unchecked exceptions. FilterInputStream and FilterOutputStream's methods throw IOException, but if I feed it a ByteArrayInputStream, or I let it filter into a ByteArrayOutputStream, then an IOException can never happen. Which could be solved by having safe and unsafe versions of the interface. Do you realize how much code duplication that would require? Exactly _BECAUSE_ you can't circumvent checked exception checking, you'd actually have to copy/paste every method. I cannot put into words the insanity of a system that would _require_ you to copy/paste vast tracts of code just to satisfy a system that is principally designed to help code maintainance. Talk about bass ackwards. In
[The Java Posse] Re: How do YOU handle Exceptions?
Ben Schulz wrote: Obviously you gained type safety, Isn't that kinda the point of a type system? :-) I suppose, but for me it's more about why I should write down the types. If we asked Gilad Bracha, he'd probably say it's a bad idea because they restrain your thinking. Me, I say it's good because the compiler can verify that all messages sent are understood by their receivers. Structural unions would get me much farther in that direction and that's where I want to go. If I understand it correctly (and I can only hope in this case) I would not need to write down any types if higher-order unification was decidable. Wouldn't that be nice? I'm all for manifest typing: http://blog.peterbecker.de/2008/05/i-manifest-typing.html But I find that the notions of anything that is X and Y and anything that is X or Y are natural concepts in such a system, which should be easily expressible. I tend to think of it in terms of Formal Concept Analysis[1], where these would be the join and meet operations in the complete lattice you get if you allow them. One nice thing is that they give you the missing type in this: interface X extends A,B {...} interface Y extends A,B {...} In Java the supertype of X and Y is not clear. It is X|Y, which in a closed world would be the same as AB. [for the reference: this is called the Dedekind-McNeill completion] While this all might sound very academic, I find it very intuitive and tend to see the same in less mathematically inclined people. Saying either X or Y and both A and B is quite natural and the fact that you can not express either statement in the current type systems is a limitation IMO. Since a complete lattice is computationally not too bad, I really wonder why no one addressed this issue yet. The cynic in me thinks it is just because programmers love thinking in trees. Peter [1] http://en.wikipedia.org/wiki/Formal_concept_analysis --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Why don't we just change checked exception from being an error to being a warning? It would not break any kind of compatibility. And as a library author, you still get the power to tell your clients that here's something to pay special attention to, but without getting in the way of people doing fast and ad-hoc prototyping/refactoring/ debugging. If this was the default behavior of checked exceptions, I would probably be for them. One could even introduce SuppressWarnings (checked) as a cleaner version of Lombok's @SneakyThrows. I have a javac where this has been done (along with converting UnreachableStatement to a warning and allow checked exception catch without a throw) and it appears to work nicely. /Casper --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
On Aug 20, 12:21 am, Peter Becker peter.becker...@gmail.com wrote: No implementation would be duplicated, the safe version could be a subtype of the unsafe one. Not too many interfaces will face that problem. To me it seems much better than not distinguishing. Can you show me how this would work? I have a hard time seeing how you can do that without (oh, the irony), employing some sort of sneakythrow mechanism. I guess we will have to agree to disagree here, but I'm fairly sure the idealism lost in allowing sneakythrow is minor, whereas the amount of pain you can solve is sizable. (in practice, due to widespread bad API design we all know will never ever get fixed, such as in the core JDK) --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
public void handleWebRequest(String target, Request req, Response res) throws Exception { @Cleanup(release) Db db = worker.getDb(); db.doWhatever(); } couldn't be simpler, really. @Cleanup is from project lombok, and it ensures the db is released even if this method errors out. Note how I just toss a 'throws Exception' on there. This is a servlet; it's effectively an entire application all by itself. That kind of broad context is allowed to throw whatever the heck it wants. The code that calls into this code catches throwable, because if a servlet errors out, even with something drastic like, say, an InternalError, it should not take the whole webserver down with it. The code that catches this does some sorting work on the exception in question, and targets a different log file if it seems particularly nasty (such as out of memory, internalerror, virtual machine error, and a few others), but that's really an implementation detail. The point is: The gazillion different instances of 'handleWebRequest' are as simple as I could make them. NB: The db object isn't passed in primarily because not all these handlers need one, and the db engine is an entirely separate module, so I'd rather avoid adding a dependency there. If I didn't have lombok, I would make Db 'lazy' and grab a connection only when a request happens, so that you don't have to try/finally this stuff, and pass a Db object into the handleWebRequest call. For you JDBC users, I suggest you go play with projectlombok.org. Here's Christian Catchpole's code sample without lombok: PreparedStatement ps = connection.prepareStatement(sql); try { ResultSet resultSet = ps.executeQuery(); try { while (resultSet.next()) { // stuff } } finally { resultSet.close(); } } finally { ps.close(); } and here's the same thing with lombok: @Cleanup PreparedStatement ps = connection.prepareStatement (sql); @Cleanup ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { // stuff } If you have a need to handle SQLExceptions locally (I would like to state again that if you are forced to do this, your framework sucks and you should fix it!), it would turn into: try { @Cleanup PreparedStatement ps = connection.prepareStatement (sql); @Cleanup ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { // stuff } } catch ( SQLException e ) { //What are ya gonna do now? } rule of thumb: If you can't do anything useful in your catch block other than log and/or wrap it, you're doing it wrong. And to the genius who mentioned beep(): Whoa. Did not know about it. Evil! Muhahaha! On Aug 18, 3:29 am, phil swenson phil.swen...@gmail.com wrote: I'm happy to see all the runtime exception advocates on here. Definitely not the mainstream view. Smart crowd :) I would love to see some example of how you guys write JDBC code. JDBC code is usually the most heinous of all with all the SQLException and resource handling crap you have to do. Please post a snippet :) On Aug 17, 6:47 pm, Michael Neale michael.ne...@gmail.com wrote: The only sane way is this: try { .. your code here } catch (Throwable t) { for (int i =0; i 1000; i++) java.awt.Toolkit.beep(); System.exit(-1); } Sometimes can use a Runtime.exec to delete the home directory for good measure, but that means platform specific code. On Aug 18, 8:58 am, Casper Bang casper.b...@gmail.com wrote: For that we have Runtime().getRuntime().addShutdownHook() no? That's what I used anyway with JSR-296, where Hans Muller had hardwired the System.exit() call in the framework. /Casper On 17 Aug., 23:11, Peter Becker peter.becker...@gmail.com wrote: Jess Holle wrote: Peter Becker wrote: While I agree that you can have shared state, the scenario I had was a clean worker: some data goes in before the thread gets started, other data comes out at the end. System.exit is a bad idea generally since you don't really know who is going to use your code in the future. If you call System.exit in your average Tomcat installation you'll probably take it down with you. I tend to restrict the System.exit calls to main(..) methods. Low-level code shouldn't be catching VirtualMachineError -- it should always re-throw it. I agree. But between the likelihood of this error being raised and the damage done if you catch it when you shouldn't the risk seems quite acceptable. Again: it is highly dependent on what your application is, I would certainly not recommend this for a mission or even life critical section of code. Only top-level thread handlers should catch these errors and call System.exit(). And
[The Java Posse] Re: How do YOU handle Exceptions?
On Aug 18, 5:27 am, phil swenson phil.swen...@gmail.com wrote: Someone should short-circuit javac, since checked exceptions really is just a figment of its imagination. Done, sort of, if you use eclipse, at any rate. Install project lombok and stick: @SneakyThrows on every method that you have. You could also dive into the lombok source code and change the SneakyThrows handler to just apply to every method, even if it does not have that annotation. It would at least be an interesting experiment to spend some time coding in plain java except with checked exceptions just disabled wholesale. There's one fairly major problem though: javac will not let you catch exceptions unless a statement in the try block is known to throw that exception, and with @SneakyThrows, that just doesn't happen anymore. I fervently hope that this restriction is removed in java 7. It's somewhat likely; Neal Gafter's idea of letting 'catch ( final Throwable t ) ' actually have t only be all types that can legally be thrown by the statements in the try block, so that you can do a general catch all and rethrow without enumerating all types, has a rare condition in which old code no longer compiles, which would be fixed if you indeed remove the restriction that you can't catch exceptions that are never thrown in the try block*. So, here's hopin' coin delivers. *) Well, you can always catch a superclass or subclass of RuntimeException and Error, but all the other ones, not so much. NB: I discovered a bug in the sneaky throws code generator for eclipse; every so often it'll make eclipse's parser get very confused and you lose your syntax highlighting. It happens somewhat rarely, and I don't have time today to figure out exactly what's causing it, but I will get around to it at some point. I made this request on the Project Coin list and was very promptly shot down. I really do wish someone would hack it into javac and have and IDE switch to turn them off. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
In Scala you get the Either type. That is superior for most cases where one might use checked exceptions in Java. I have used that style in Java, but you usually don't make friends with it. Peter Michael Neale wrote: What do people think of the scala approach of no checked exceptions - even checked exceptions are not treated specially by the constructor (personally, I like it). On Aug 18, 12:55 pm, Christian Catchpole christ...@catchpole.net wrote: No, i just let that go up. I really try to avoid the declare as null then set thingy. On Aug 18, 12:03 pm, Casper Bang casper.b...@gmail.com wrote: You neglect to handle the checked exception declared by prepareStatement no? PreparedStatement stmt = null; try{ stmt = connection.prepareStatement(sql); final ResultSet rs = stmt.executeQuery(); try{ while (rs.next()){ // Stuff... { } finally{ rs.close(); }} catch(SQLException e){ // Logging...} finally{ try{ stmt.close(); } catch(SQLException whoTheFuckCares){ }; } Really, how many other ways are there to do it I wonder now? (Apart from wrapping certain things, like the last try-catch clause in some general purpose closer util?). /Casper --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
I still believe that the main reason people hate checked exceptions is that they have been used badly. But I don't really like them either, I just dislike runtime exceptions more ;-) The reason for that is that they hide things I might want to know about when using an API. No one reads documentation well enough, the enforcement checked exceptions give you is quite useful -- at least given the context of Java. And I don't buy into the just unit test argument, things like SQLException and IOException rarely happen in test environments unless the test was designed to test just that -- it is the exceptional case you don't expect that scares me. What I would really like to see is a meet/or/disjunction/union operator in the type system, with a case-like construct to resolve the resulting types. Scala has two things that are halfway there (Either, case classes), but neither is the full monty. Peter phil swenson wrote: there is a reason no other language ever written has checked exceptions - checked exceptions are a bad idea. On my first java project back in 1999 I remember adding in a checked exception to a utility class. It has effects on hundreds of classes and 1000s of method calls. I then decided it was more trouble than it was worth and switched everything to runtime exceptions. Worked brilliantly. Checked exceptions almost always degenerate into throws exception on 100s to 1000s of methods in your project. They simply don't scale, one small change can ripple through an entire project. They also lead to try{blahblah}catch(Exception e}{} (exception hiding). They lead to logging the exception multiple times (catch, log, rethrow), giant method signatures, exception wrapping, and other harmful practices. The correct (IMO) way to handle it is to let the exception bubble up to the top level thread and handle it there, whether it's present to the user, log, and/or cancel a transaction. Exceptions almost never can be recovered from and people are almost always fooling themselves if they think they can. I think 95+% of the time exceptions are from bugs, not from recoverable situations. People try to build hugely fault tolerant systems and they end up hiding bugs. In the rare case that you want to handle an exception at a lower level, do it. But you certainly don't want this to be the default behavior, it's the EXCEPTIONAL case. :) On Aug 17, 9:10 pm, Michael Neale michael.ne...@gmail.com wrote: What do people think of the scala approach of no checked exceptions - even checked exceptions are not treated specially by the constructor (personally, I like it). On Aug 18, 12:55 pm, Christian Catchpole christ...@catchpole.net wrote: No, i just let that go up. I really try to avoid the declare as null then set thingy. On Aug 18, 12:03 pm, Casper Bang casper.b...@gmail.com wrote: You neglect to handle the checked exception declared by prepareStatement no? PreparedStatement stmt = null; try{ stmt = connection.prepareStatement(sql); final ResultSet rs = stmt.executeQuery(); try{ while (rs.next()){ // Stuff... { } finally{ rs.close(); }} catch(SQLException e){ // Logging...} finally{ try{ stmt.close(); } catch(SQLException whoTheFuckCares){ }; } Really, how many other ways are there to do it I wonder now? (Apart from wrapping certain things, like the last try-catch clause in some general purpose closer util?). /Casper --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
The problem I feel is that an Exception should denote an EXCEPTIONAL occurrence, and be able to list all things that can happen is just plain impossible. So switching to a fully checked exceptions would mean that every method signature should mandatory include stuff like: public void foo(Bar bar) throws TheSkyIsFallingException, HellFrozeOverException, ShitInShitOutException etc. While you could say that all these exceptions are EntropyExceptions you could say: public void foo(Bar bar) throws EntropyException But why stop at that? You might as well generalize it into public void foo(Bar bar) throws Exception And if you know that every method can throw an exception, you might as well say that public void foo(Bar bar) implicit throws Exception And, then you basically have RuntimeException On Tue, Aug 18, 2009 at 12:13 PM, Peter Becker peter.becker...@gmail.comwrote: I still believe that the main reason people hate checked exceptions is that they have been used badly. But I don't really like them either, I just dislike runtime exceptions more ;-) The reason for that is that they hide things I might want to know about when using an API. No one reads documentation well enough, the enforcement checked exceptions give you is quite useful -- at least given the context of Java. And I don't buy into the just unit test argument, things like SQLException and IOException rarely happen in test environments unless the test was designed to test just that -- it is the exceptional case you don't expect that scares me. What I would really like to see is a meet/or/disjunction/union operator in the type system, with a case-like construct to resolve the resulting types. Scala has two things that are halfway there (Either, case classes), but neither is the full monty. Peter phil swenson wrote: there is a reason no other language ever written has checked exceptions - checked exceptions are a bad idea. On my first java project back in 1999 I remember adding in a checked exception to a utility class. It has effects on hundreds of classes and 1000s of method calls. I then decided it was more trouble than it was worth and switched everything to runtime exceptions. Worked brilliantly. Checked exceptions almost always degenerate into throws exception on 100s to 1000s of methods in your project. They simply don't scale, one small change can ripple through an entire project. They also lead to try{blahblah}catch(Exception e}{} (exception hiding). They lead to logging the exception multiple times (catch, log, rethrow), giant method signatures, exception wrapping, and other harmful practices. The correct (IMO) way to handle it is to let the exception bubble up to the top level thread and handle it there, whether it's present to the user, log, and/or cancel a transaction. Exceptions almost never can be recovered from and people are almost always fooling themselves if they think they can. I think 95+% of the time exceptions are from bugs, not from recoverable situations. People try to build hugely fault tolerant systems and they end up hiding bugs. In the rare case that you want to handle an exception at a lower level, do it. But you certainly don't want this to be the default behavior, it's the EXCEPTIONAL case. :) On Aug 17, 9:10 pm, Michael Neale michael.ne...@gmail.com wrote: What do people think of the scala approach of no checked exceptions - even checked exceptions are not treated specially by the constructor (personally, I like it). On Aug 18, 12:55 pm, Christian Catchpole christ...@catchpole.net wrote: No, i just let that go up. I really try to avoid the declare as null then set thingy. On Aug 18, 12:03 pm, Casper Bang casper.b...@gmail.com wrote: You neglect to handle the checked exception declared by prepareStatement no? PreparedStatement stmt = null; try{ stmt = connection.prepareStatement(sql); final ResultSet rs = stmt.executeQuery(); try{ while (rs.next()){ // Stuff... { } finally{ rs.close(); }} catch(SQLException e){ // Logging...} finally{ try{ stmt.close(); } catch(SQLException whoTheFuckCares){ }; } Really, how many other ways are there to do it I wonder now? (Apart from wrapping certain things, like the last try-catch clause in some general purpose closer util?). /Casper -- Viktor Klang Rogue Scala-head Blog: klangism.blogspot.com Twttr: viktorklang --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at
[The Java Posse] Re: How do YOU handle Exceptions?
Regarding closing JDBC resources when exceptions happen... I like to have one close in the 'finally' block, but execute only when the reference isn't null. (Yes, that's evil -- but JDBC's SQLException is evil.) What I'd like to do is to add any 'close()' SQLException to the exception that may have triggered the 'finally' block. But that's not easy. Not standard Java either: Java supports caused by, but not collections of exceptions. :-[ --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Reinier Zwitserloot wrote: Yes, an utopia with checked exceptions is probably pretty decent, but as a practical matter they've been horribly abused. Not just by third party libraries; the java core library is inconsistent in places and has a lot of missing throws clauses in interfaces that can't be fixed because it would break backwards compatibility. Trying to fix these things is going to be even more painful than having to deal with checked exceptions in the current circumstance, which is one of the reasons why I advocate solving the problem directly. Such as offering an opt out mechanism where a programmer can explicitly 'correct' the compiler to say: Yah, I know, I know, this method call here DECLARES that it'll throw SomeCheckedException, and I neither catch it nor declare to throw it onwards, but, shaddap. I know what I'm doing, just compile this code, and let me get on with my day. It'll be abused, but the notion that exceptions will be abused in some fashion is what we have to deal with. The question is: How can we make sure the abuse is kept to a minimum? I'd assert that try {} catch ( Throwable t ) { Log.log(t); } is a much worse abuse than sneakythrowing. Agreed. You get the benefit of being explicitly told about the checked exceptions that you ought to be checking, but when the theory fails due to a practical matter (the declared exception can't possibly happen, or you want to throw the exception onward but due to a badly designed interface you're not allowed to, etc, etc), you won't have to jump through a bunch of hoops, obscuring the exception as you go. Being able to return a disjoint type so you can cover extraordinary exit conditions that way instead of throwing exceptions for them could work, but I don't really know of any language that handles them all that well. The only way I can see how it could possibly work is pattern matching. Which scala can mostly do, can't it? As far as I understand you can't just do something like this (in Java-like syntax, but ignoring a few other things Java such as the .class for types): public Result|Error1|Error2 someMethod() {...} public void someOtherMethod() { var result = someMethod(); switch(typeof result) { case Result: processResult(result); default: handleError(result); } } public void processResult(Result result) {...} public void handleError(Error1|Error2 error) { ...code using anything on common supertypes of Error1/2... } Part of what I'd like to see is that there is no need to name the types used. The signature of the last method should also be allowed to be handleError(Error) assuming that both Error1 nad Error2 are subtypes of Error (which is really just normal polymorphism since it implies that the union is a subtype, too). My Scala is not good enough to judge what is truly possible, but most code I've seen seems to end up using Either in this case, which seems a bit of a kludge -- particularly if you create a union of more than two types. I'd be happy to hear about alternatives. Peter On Aug 18, 12:13 pm, Peter Becker peter.becker...@gmail.com wrote: I still believe that the main reason people hate checked exceptions is that they have been used badly. But I don't really like them either, I just dislike runtime exceptions more ;-) The reason for that is that they hide things I might want to know about when using an API. No one reads documentation well enough, the enforcement checked exceptions give you is quite useful -- at least given the context of Java. And I don't buy into the just unit test argument, things like SQLException and IOException rarely happen in test environments unless the test was designed to test just that -- it is the exceptional case you don't expect that scares me. What I would really like to see is a meet/or/disjunction/union operator in the type system, with a case-like construct to resolve the resulting types. Scala has two things that are halfway there (Either, case classes), but neither is the full monty. Peter phil swenson wrote: there is a reason no other language ever written has checked exceptions - checked exceptions are a bad idea. On my first java project back in 1999 I remember adding in a checked exception to a utility class. It has effects on hundreds of classes and 1000s of method calls. I then decided it was more trouble than it was worth and switched everything to runtime exceptions. Worked brilliantly. Checked exceptions almost always degenerate into throws exception on 100s to 1000s of methods in your project. They simply don't scale, one small change can ripple through an entire project. They also lead to try{blahblah}catch(Exception e}{} (exception hiding). They lead to logging the exception multiple times (catch, log, rethrow), giant method signatures, exception wrapping, and other harmful practices. The correct (IMO)
[The Java Posse] Re: How do YOU handle Exceptions?
Lombok - is that named after Lombok in bali - near the island of Java? On Aug 18, 5:00 pm, Reinier Zwitserloot reini...@gmail.com wrote: public void handleWebRequest(String target, Request req, Response res) throws Exception { @Cleanup(release) Db db = worker.getDb(); db.doWhatever(); } couldn't be simpler, really. @Cleanup is from project lombok, and it ensures the db is released even if this method errors out. Note how I just toss a 'throws Exception' on there. This is a servlet; it's effectively an entire application all by itself. That kind of broad context is allowed to throw whatever the heck it wants. The code that calls into this code catches throwable, because if a servlet errors out, even with something drastic like, say, an InternalError, it should not take the whole webserver down with it. The code that catches this does some sorting work on the exception in question, and targets a different log file if it seems particularly nasty (such as out of memory, internalerror, virtual machine error, and a few others), but that's really an implementation detail. The point is: The gazillion different instances of 'handleWebRequest' are as simple as I could make them. NB: The db object isn't passed in primarily because not all these handlers need one, and the db engine is an entirely separate module, so I'd rather avoid adding a dependency there. If I didn't have lombok, I would make Db 'lazy' and grab a connection only when a request happens, so that you don't have to try/finally this stuff, and pass a Db object into the handleWebRequest call. For you JDBC users, I suggest you go play with projectlombok.org. Here's Christian Catchpole's code sample without lombok: PreparedStatement ps = connection.prepareStatement(sql); try { ResultSet resultSet = ps.executeQuery(); try { while (resultSet.next()) { // stuff } } finally { resultSet.close(); } } finally { ps.close(); } and here's the same thing with lombok: @Cleanup PreparedStatement ps = connection.prepareStatement (sql); @Cleanup ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { // stuff } If you have a need to handle SQLExceptions locally (I would like to state again that if you are forced to do this, your framework sucks and you should fix it!), it would turn into: try { @Cleanup PreparedStatement ps = connection.prepareStatement (sql); @Cleanup ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { // stuff }} catch ( SQLException e ) { //What are ya gonna do now? } rule of thumb: If you can't do anything useful in your catch block other than log and/or wrap it, you're doing it wrong. And to the genius who mentioned beep(): Whoa. Did not know about it. Evil! Muhahaha! On Aug 18, 3:29 am, phil swenson phil.swen...@gmail.com wrote: I'm happy to see all the runtime exception advocates on here. Definitely not the mainstream view. Smart crowd :) I would love to see some example of how you guys write JDBC code. JDBC code is usually the most heinous of all with all the SQLException and resource handling crap you have to do. Please post a snippet :) On Aug 17, 6:47 pm, Michael Neale michael.ne...@gmail.com wrote: The only sane way is this: try { .. your code here } catch (Throwable t) { for (int i =0; i 1000; i++) java.awt.Toolkit.beep(); System.exit(-1); } Sometimes can use a Runtime.exec to delete the home directory for good measure, but that means platform specific code. On Aug 18, 8:58 am, Casper Bang casper.b...@gmail.com wrote: For that we have Runtime().getRuntime().addShutdownHook() no? That's what I used anyway with JSR-296, where Hans Muller had hardwired the System.exit() call in the framework. /Casper On 17 Aug., 23:11, Peter Becker peter.becker...@gmail.com wrote: Jess Holle wrote: Peter Becker wrote: While I agree that you can have shared state, the scenario I had was a clean worker: some data goes in before the thread gets started, other data comes out at the end. System.exit is a bad idea generally since you don't really know who is going to use your code in the future. If you call System.exit in your average Tomcat installation you'll probably take it down with you. I tend to restrict the System.exit calls to main(..) methods. Low-level code shouldn't be catching VirtualMachineError -- it should always re-throw it. I agree. But between the likelihood of this error being raised and the damage done if you catch it when you shouldn't the risk seems quite
[The Java Posse] Re: How do YOU handle Exceptions?
Is it really that bad? Most of the common exceptions shouldn't be there at all, for example NullPointerException, ClassCastException and ArrayStoreException are all just signs of a broken type system. Some of the Errors seem unavoidable, but with the Exceptions I still prefer the idea of actually managing them. Note that one of the most important patterns for me is chained exceptions. Somehow it took until JDK 1.4 until they got introduced and even then not completely. But by chaining exceptions you can keep the number of exceptions in each layer down and you also provide encapsulation. In the end it comes down to a lot of different factors, including personal taste. But I am still not willing to dismiss checked exceptions as a generally bad idea. Peter Viktor Klang wrote: The problem I feel is that an Exception should denote an EXCEPTIONAL occurrence, and be able to list all things that can happen is just plain impossible. So switching to a fully checked exceptions would mean that every method signature should mandatory include stuff like: public void foo(Bar bar) throws TheSkyIsFallingException, HellFrozeOverException, ShitInShitOutException etc. While you could say that all these exceptions are EntropyExceptions you could say: public void foo(Bar bar) throws EntropyException But why stop at that? You might as well generalize it into public void foo(Bar bar) throws Exception And if you know that every method can throw an exception, you might as well say that public void foo(Bar bar) implicit throws Exception And, then you basically have RuntimeException On Tue, Aug 18, 2009 at 12:13 PM, Peter Becker peter.becker.de http://peter.becker.de@gmail.com http://gmail.com wrote: I still believe that the main reason people hate checked exceptions is that they have been used badly. But I don't really like them either, I just dislike runtime exceptions more ;-) The reason for that is that they hide things I might want to know about when using an API. No one reads documentation well enough, the enforcement checked exceptions give you is quite useful -- at least given the context of Java. And I don't buy into the just unit test argument, things like SQLException and IOException rarely happen in test environments unless the test was designed to test just that -- it is the exceptional case you don't expect that scares me. What I would really like to see is a meet/or/disjunction/union operator in the type system, with a case-like construct to resolve the resulting types. Scala has two things that are halfway there (Either, case classes), but neither is the full monty. Peter phil swenson wrote: there is a reason no other language ever written has checked exceptions - checked exceptions are a bad idea. On my first java project back in 1999 I remember adding in a checked exception to a utility class. It has effects on hundreds of classes and 1000s of method calls. I then decided it was more trouble than it was worth and switched everything to runtime exceptions. Worked brilliantly. Checked exceptions almost always degenerate into throws exception on 100s to 1000s of methods in your project. They simply don't scale, one small change can ripple through an entire project. They also lead to try{blahblah}catch(Exception e}{} (exception hiding). They lead to logging the exception multiple times (catch, log, rethrow), giant method signatures, exception wrapping, and other harmful practices. The correct (IMO) way to handle it is to let the exception bubble up to the top level thread and handle it there, whether it's present to the user, log, and/or cancel a transaction. Exceptions almost never can be recovered from and people are almost always fooling themselves if they think they can. I think 95+% of the time exceptions are from bugs, not from recoverable situations. People try to build hugely fault tolerant systems and they end up hiding bugs. In the rare case that you want to handle an exception at a lower level, do it. But you certainly don't want this to be the default behavior, it's the EXCEPTIONAL case. :) On Aug 17, 9:10 pm, Michael Neale michael.ne...@gmail.com mailto:michael.ne...@gmail.com wrote: What do people think of the scala approach of no checked exceptions - even checked exceptions are not treated specially by the constructor (personally, I like it). On Aug 18, 12:55 pm, Christian Catchpole christ...@catchpole.net mailto:christ...@catchpole.net wrote: No, i just let that go up. I really try to avoid the declare as null then set
[The Java Posse] Re: How do YOU handle Exceptions?
Proably would use a set of case classes I guess, but would end up looking like a pretty version of that (someone like Viktor will probably show us !). On Aug 18, 9:11 pm, Peter Becker peter.becker...@gmail.com wrote: Reinier Zwitserloot wrote: Yes, an utopia with checked exceptions is probably pretty decent, but as a practical matter they've been horribly abused. Not just by third party libraries; the java core library is inconsistent in places and has a lot of missing throws clauses in interfaces that can't be fixed because it would break backwards compatibility. Trying to fix these things is going to be even more painful than having to deal with checked exceptions in the current circumstance, which is one of the reasons why I advocate solving the problem directly. Such as offering an opt out mechanism where a programmer can explicitly 'correct' the compiler to say: Yah, I know, I know, this method call here DECLARES that it'll throw SomeCheckedException, and I neither catch it nor declare to throw it onwards, but, shaddap. I know what I'm doing, just compile this code, and let me get on with my day. It'll be abused, but the notion that exceptions will be abused in some fashion is what we have to deal with. The question is: How can we make sure the abuse is kept to a minimum? I'd assert that try {} catch ( Throwable t ) { Log.log(t); } is a much worse abuse than sneakythrowing. Agreed. You get the benefit of being explicitly told about the checked exceptions that you ought to be checking, but when the theory fails due to a practical matter (the declared exception can't possibly happen, or you want to throw the exception onward but due to a badly designed interface you're not allowed to, etc, etc), you won't have to jump through a bunch of hoops, obscuring the exception as you go. Being able to return a disjoint type so you can cover extraordinary exit conditions that way instead of throwing exceptions for them could work, but I don't really know of any language that handles them all that well. The only way I can see how it could possibly work is pattern matching. Which scala can mostly do, can't it? As far as I understand you can't just do something like this (in Java-like syntax, but ignoring a few other things Java such as the .class for types): public Result|Error1|Error2 someMethod() {...} public void someOtherMethod() { var result = someMethod(); switch(typeof result) { case Result: processResult(result); default: handleError(result); } } public void processResult(Result result) {...} public void handleError(Error1|Error2 error) { ...code using anything on common supertypes of Error1/2... } Part of what I'd like to see is that there is no need to name the types used. The signature of the last method should also be allowed to be handleError(Error) assuming that both Error1 nad Error2 are subtypes of Error (which is really just normal polymorphism since it implies that the union is a subtype, too). My Scala is not good enough to judge what is truly possible, but most code I've seen seems to end up using Either in this case, which seems a bit of a kludge -- particularly if you create a union of more than two types. I'd be happy to hear about alternatives. Peter On Aug 18, 12:13 pm, Peter Becker peter.becker...@gmail.com wrote: I still believe that the main reason people hate checked exceptions is that they have been used badly. But I don't really like them either, I just dislike runtime exceptions more ;-) The reason for that is that they hide things I might want to know about when using an API. No one reads documentation well enough, the enforcement checked exceptions give you is quite useful -- at least given the context of Java. And I don't buy into the just unit test argument, things like SQLException and IOException rarely happen in test environments unless the test was designed to test just that -- it is the exceptional case you don't expect that scares me. What I would really like to see is a meet/or/disjunction/union operator in the type system, with a case-like construct to resolve the resulting types. Scala has two things that are halfway there (Either, case classes), but neither is the full monty. Peter phil swenson wrote: there is a reason no other language ever written has checked exceptions - checked exceptions are a bad idea. On my first java project back in 1999 I remember adding in a checked exception to a utility class. It has effects on hundreds of classes and 1000s of method calls. I then decided it was more trouble than it was worth and switched everything to runtime exceptions. Worked brilliantly. Checked exceptions almost always degenerate into throws exception on 100s to 1000s of methods in your project. They simply don't scale, one small change can ripple through an
[The Java Posse] Re: How do YOU handle Exceptions?
Lombok looks interesting. Groovy makes this sort of code very palatable too, instead of: @Cleanup PreparedStatement ps = connection.prepareStatement (sql); @Cleanup ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { // stuff } You would do: sql.eachRow(sql) { /* stuff */ } On Tue, Aug 18, 2009 at 5:00 PM, Reinier Zwitserlootreini...@gmail.com wrote: public void handleWebRequest(String target, Request req, Response res) throws Exception { �...@cleanup(release) Db db = worker.getDb(); db.doWhatever(); } couldn't be simpler, really. @Cleanup is from project lombok, and it ensures the db is released even if this method errors out. Note how I just toss a 'throws Exception' on there. This is a servlet; it's effectively an entire application all by itself. That kind of broad context is allowed to throw whatever the heck it wants. The code that calls into this code catches throwable, because if a servlet errors out, even with something drastic like, say, an InternalError, it should not take the whole webserver down with it. The code that catches this does some sorting work on the exception in question, and targets a different log file if it seems particularly nasty (such as out of memory, internalerror, virtual machine error, and a few others), but that's really an implementation detail. The point is: The gazillion different instances of 'handleWebRequest' are as simple as I could make them. NB: The db object isn't passed in primarily because not all these handlers need one, and the db engine is an entirely separate module, so I'd rather avoid adding a dependency there. If I didn't have lombok, I would make Db 'lazy' and grab a connection only when a request happens, so that you don't have to try/finally this stuff, and pass a Db object into the handleWebRequest call. For you JDBC users, I suggest you go play with projectlombok.org. Here's Christian Catchpole's code sample without lombok: PreparedStatement ps = connection.prepareStatement(sql); try { ResultSet resultSet = ps.executeQuery(); try { while (resultSet.next()) { // stuff } } finally { resultSet.close(); } } finally { ps.close(); } and here's the same thing with lombok: �...@cleanup PreparedStatement ps = connection.prepareStatement (sql); �...@cleanup ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { // stuff } If you have a need to handle SQLExceptions locally (I would like to state again that if you are forced to do this, your framework sucks and you should fix it!), it would turn into: try { �...@cleanup PreparedStatement ps = connection.prepareStatement (sql); �...@cleanup ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { // stuff } } catch ( SQLException e ) { //What are ya gonna do now? } rule of thumb: If you can't do anything useful in your catch block other than log and/or wrap it, you're doing it wrong. And to the genius who mentioned beep(): Whoa. Did not know about it. Evil! Muhahaha! On Aug 18, 3:29 am, phil swenson phil.swen...@gmail.com wrote: I'm happy to see all the runtime exception advocates on here. Definitely not the mainstream view. Smart crowd :) I would love to see some example of how you guys write JDBC code. JDBC code is usually the most heinous of all with all the SQLException and resource handling crap you have to do. Please post a snippet :) On Aug 17, 6:47 pm, Michael Neale michael.ne...@gmail.com wrote: The only sane way is this: try { .. your code here } catch (Throwable t) { for (int i =0; i 1000; i++) java.awt.Toolkit.beep(); System.exit(-1); } Sometimes can use a Runtime.exec to delete the home directory for good measure, but that means platform specific code. On Aug 18, 8:58 am, Casper Bang casper.b...@gmail.com wrote: For that we have Runtime().getRuntime().addShutdownHook() no? That's what I used anyway with JSR-296, where Hans Muller had hardwired the System.exit() call in the framework. /Casper On 17 Aug., 23:11, Peter Becker peter.becker...@gmail.com wrote: Jess Holle wrote: Peter Becker wrote: While I agree that you can have shared state, the scenario I had was a clean worker: some data goes in before the thread gets started, other data comes out at the end. System.exit is a bad idea generally since you don't really know who is going to use your code in the future. If you call System.exit in your average Tomcat installation you'll probably take it down with you. I tend to restrict the System.exit calls to main(..) methods. Low-level code shouldn't be
[The Java Posse] Re: How do YOU handle Exceptions?
I guess should have used a different variable name in the last example: db.eachRow(sql) { /* stuff */ } Cheers, Paul. On Tue, Aug 18, 2009 at 11:37 PM, Paul Kingpaul.king.as...@gmail.com wrote: Lombok looks interesting. Groovy makes this sort of code very palatable too, instead of: �...@cleanup PreparedStatement ps = connection.prepareStatement (sql); �...@cleanup ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { // stuff } You would do: sql.eachRow(sql) { /* stuff */ } On Tue, Aug 18, 2009 at 5:00 PM, Reinier Zwitserlootreini...@gmail.com wrote: public void handleWebRequest(String target, Request req, Response res) throws Exception { �...@cleanup(release) Db db = worker.getDb(); db.doWhatever(); } couldn't be simpler, really. @Cleanup is from project lombok, and it ensures the db is released even if this method errors out. Note how I just toss a 'throws Exception' on there. This is a servlet; it's effectively an entire application all by itself. That kind of broad context is allowed to throw whatever the heck it wants. The code that calls into this code catches throwable, because if a servlet errors out, even with something drastic like, say, an InternalError, it should not take the whole webserver down with it. The code that catches this does some sorting work on the exception in question, and targets a different log file if it seems particularly nasty (such as out of memory, internalerror, virtual machine error, and a few others), but that's really an implementation detail. The point is: The gazillion different instances of 'handleWebRequest' are as simple as I could make them. NB: The db object isn't passed in primarily because not all these handlers need one, and the db engine is an entirely separate module, so I'd rather avoid adding a dependency there. If I didn't have lombok, I would make Db 'lazy' and grab a connection only when a request happens, so that you don't have to try/finally this stuff, and pass a Db object into the handleWebRequest call. For you JDBC users, I suggest you go play with projectlombok.org. Here's Christian Catchpole's code sample without lombok: PreparedStatement ps = connection.prepareStatement(sql); try { ResultSet resultSet = ps.executeQuery(); try { while (resultSet.next()) { // stuff } } finally { resultSet.close(); } } finally { ps.close(); } and here's the same thing with lombok: �...@cleanup PreparedStatement ps = connection.prepareStatement (sql); �...@cleanup ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { // stuff } If you have a need to handle SQLExceptions locally (I would like to state again that if you are forced to do this, your framework sucks and you should fix it!), it would turn into: try { �...@cleanup PreparedStatement ps = connection.prepareStatement (sql); �...@cleanup ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { // stuff } } catch ( SQLException e ) { //What are ya gonna do now? } rule of thumb: If you can't do anything useful in your catch block other than log and/or wrap it, you're doing it wrong. And to the genius who mentioned beep(): Whoa. Did not know about it. Evil! Muhahaha! On Aug 18, 3:29 am, phil swenson phil.swen...@gmail.com wrote: I'm happy to see all the runtime exception advocates on here. Definitely not the mainstream view. Smart crowd :) I would love to see some example of how you guys write JDBC code. JDBC code is usually the most heinous of all with all the SQLException and resource handling crap you have to do. Please post a snippet :) On Aug 17, 6:47 pm, Michael Neale michael.ne...@gmail.com wrote: The only sane way is this: try { .. your code here } catch (Throwable t) { for (int i =0; i 1000; i++) java.awt.Toolkit.beep(); System.exit(-1); } Sometimes can use a Runtime.exec to delete the home directory for good measure, but that means platform specific code. On Aug 18, 8:58 am, Casper Bang casper.b...@gmail.com wrote: For that we have Runtime().getRuntime().addShutdownHook() no? That's what I used anyway with JSR-296, where Hans Muller had hardwired the System.exit() call in the framework. /Casper On 17 Aug., 23:11, Peter Becker peter.becker...@gmail.com wrote: Jess Holle wrote: Peter Becker wrote: While I agree that you can have shared state, the scenario I had was a clean worker: some data goes in before the thread gets started, other data comes out at the end. System.exit is a bad idea generally since you don't really know who is going to use your code in the future. If you
[The Java Posse] Re: How do YOU handle Exceptions?
Maybe what this discussion needs is some real-world anecdotes of checked vs unchecked exceptions in production environments and how they helped or not to save the day. Alexey 2001 Honda CBR600F4i (CCS) 1992 Kawasaki EX500 http://azinger.blogspot.com http://bsheet.sourceforge.net http://wcollage.sourceforge.net From: Peter Becker peter.becker...@gmail.com To: javaposse@googlegroups.com Sent: Tuesday, August 18, 2009 6:13:54 AM Subject: [The Java Posse] Re: How do YOU handle Exceptions? I still believe that the main reason people hate checked exceptions is that they have been used badly. But I don't really like them either, I just dislike runtime exceptions more ;-) The reason for that is that they hide things I might want to know about when using an API. No one reads documentation well enough, the enforcement checked exceptions give you is quite useful -- at least given the context of Java. And I don't buy into the just unit test argument, things like SQLException and IOException rarely happen in test environments unless the test was designed to test just that -- it is the exceptional case you don't expect that scares me. What I would really like to see is a meet/or/disjunction/union operator in the type system, with a case-like construct to resolve the resulting types. Scala has two things that are halfway there (Either, case classes), but neither is the full monty. Peter phil swenson wrote: there is a reason no other language ever written has checked exceptions - checked exceptions are a bad idea. On my first java project back in 1999 I remember adding in a checked exception to a utility class. It has effects on hundreds of classes and 1000s of method calls. I then decided it was more trouble than it was worth and switched everything to runtime exceptions. Worked brilliantly. Checked exceptions almost always degenerate into throws exception on 100s to 1000s of methods in your project. They simply don't scale, one small change can ripple through an entire project. They also lead to try{blahblah}catch(Exception e}{} (exception hiding). They lead to logging the exception multiple times (catch, log, rethrow), giant method signatures, exception wrapping, and other harmful practices. The correct (IMO) way to handle it is to let the exception bubble up to the top level thread and handle it there, whether it's present to the user, log, and/or cancel a transaction. Exceptions almost never can be recovered from and people are almost always fooling themselves if they think they can. I think 95+% of the time exceptions are from bugs, not from recoverable situations. People try to build hugely fault tolerant systems and they end up hiding bugs. In the rare case that you want to handle an exception at a lower level, do it. But you certainly don't want this to be the default behavior, it's the EXCEPTIONAL case. :) On Aug 17, 9:10 pm, Michael Neale michael.ne...@gmail.com wrote: What do people think of the scala approach of no checked exceptions - even checked exceptions are not treated specially by the constructor (personally, I like it). On Aug 18, 12:55 pm, Christian Catchpole christ...@catchpole.net wrote: No, i just let that go up. I really try to avoid the declare as null then set thingy. On Aug 18, 12:03 pm, Casper Bang casper.b...@gmail.com wrote: You neglect to handle the checked exception declared by prepareStatement no? PreparedStatement stmt = null; try{ stmt = connection.prepareStatement(sql); final ResultSet rs = stmt.executeQuery(); try{ while (rs.next()){ // Stuff... { } finally{ rs.close(); }} catch(SQLException e){ // Logging...} finally{ try{ stmt.close(); } catch(SQLException whoTheFuckCares){ }; } Really, how many other ways are there to do it I wonder now? (Apart from wrapping certain things, like the last try-catch clause in some general purpose closer util?). /Casper --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
On 18 Aug., 16:51, Alexey Zinger inline_f...@yahoo.com wrote: Maybe what this discussion needs is some real-world anecdotes of checked vs unchecked exceptions in production environments and how they helped or not to save the day. I would think it's a fairly real-world anecdote how no other language following Java introduced checked exceptions. Also you will have a much easier job coming up with language guro's against them than for them I think. /Casper --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
On Aug 18, 11:03 am, Casper Bang casper.b...@gmail.com wrote: On 18 Aug., 16:51, Alexey Zinger inline_f...@yahoo.com wrote: Maybe what this discussion needs is some real-world anecdotes of checked vs unchecked exceptions in production environments and how they helped or not to save the day. I would think it's a fairly real-world anecdote how no other language following Java introduced checked exceptions. Also you will have a much easier job coming up with language guro's against them than for them I think. I'm not convinced of that. So far, most of the complaints come from people talking about the imposition checked exceptions create on the coder. There's grumbling of misuse and hiding of exceptions by improper logging or catching and ignoring, but not much in the way of real-world scenarios. Not saying those statements aren't grounded in reality, but let's throw out some concrete situations to dissect and see how they could have been helped. I'm not a fan of how checked exceptions are used in specific API, JSE included, but I'm not against the concept as a whole. Lately, I've been working almost exclusively on web projects, many of them using GWT. Some of those projects were started by my predecessor and, not to put the guy down, but there's some horrendous exception handling there. Lots of catch(Exception), inconsistent and often broken logging, and all sorts of nasties like that. Some of the scenarios that were very difficult to debug (and still are in some parts of the systems) are the ones, where there's use of a 3rd party Excel authoring library (jxl as I recall). Occasionally, the code comes across a situation that breaks certain assumptions (unexpected formatting, or the like) and those almost inevitably get buried in ignored exception catches. I never get proper time to go through it (not that I'm that excited to do it) and clean it up, and so time and again we bump into some new extravagant way the system breaks. Now, one would read this and say, Aha! -- if only there were no checked exceptions, your predecessor would have written his sloppy code in a way that would allow those to propagate to the top layer (servlet container) and you would have seen it in some log and probably on some screen. Indeed, some of those exceptions are of checked variety. However, the code was written in a manner that didn't stand a chance. He simply assumed there would be no erroneous situation and dealt wrote EVERYTHING (file IO, DB, parsing/formatting, etc.) under a single try block and figured he'd just log whatever was caught in one catch (reuse, right?). And in fact, there ARE plenty of ways to handle these situations based on whatever kind of exception might arise. For instance, multiple formats might be tried on a single value before giving up, whereas a general Excel file read exception is probably unrecoverable. And then there's the unintended catching of RuntimeException that's sprinkled around there that also just lumps lots of different situations into one try/catch. This one can't be fixed by killing off checked exceptions, obviously. Overall, much of the problems could have been avoided by a better internal API design, that would separate different layers of functionality into finer granularity and would make it clear to the developer how to handle each and every exceptional situation differently, while still cleaning up resources when possible. So I don't think simply eliminating checked exceptions would have been the answer. I think both checked and unchecked have their place. Remember, that just because Java is the only language with checked exceptions, doesn't mean that it's a dead end. I do think that real world implementations have scared some people off the idea. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
I understand the theoretical benefit of checked exceptions, but reality trumps theory. They simply don't scale and lead to swallowed/ hidden exceptions. I've seen quite a few open source APIs that have throws Exception in them. And generally the open source APIs are done by some of the best coders! Another issue I didn't mention is checked exceptions pollute the interface. Lets say you have a public API (interface) and add a new exception type. This makes every consumer of your API's code break. This violates the concept of having an API contract. So with checked exceptions either you are forced to 1) violate the contract or 2) not throw the exception you want to throw and wrap it in an unsuitable exception or 3) use a runtime exception. 3 is best:) people are so concerned with not knowing what exceptions are thrown, but if you test your projects you will discover when there are exceptions that are thrown and you want to handle. It's a rare occurrence. usually there is nothing you can do about it, so knowing that it will be thrown doesn't really help you out. I mean seriously, what do you do when you get a SQL Exception? it's almost always a bug. and a bug that might not be discovered if you used a checked exception and swallowed it. On Aug 18, 4:13 am, Peter Becker peter.becker...@gmail.com wrote: I still believe that the main reason people hate checked exceptions is that they have been used badly. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Yes. And the indonesian word for chili paste, which is also lombok. (Spice up your java is the tag line, after all.) On Aug 18, 1:22 pm, Michael Neale michael.ne...@gmail.com wrote: Lombok - is that named after Lombok in bali - near the island of Java? On Aug 18, 5:00 pm, Reinier Zwitserloot reini...@gmail.com wrote: public void handleWebRequest(String target, Request req, Response res) throws Exception { @Cleanup(release) Db db = worker.getDb(); db.doWhatever(); } couldn't be simpler, really. @Cleanup is from project lombok, and it ensures the db is released even if this method errors out. Note how I just toss a 'throws Exception' on there. This is a servlet; it's effectively an entire application all by itself. That kind of broad context is allowed to throw whatever the heck it wants. The code that calls into this code catches throwable, because if a servlet errors out, even with something drastic like, say, an InternalError, it should not take the whole webserver down with it. The code that catches this does some sorting work on the exception in question, and targets a different log file if it seems particularly nasty (such as out of memory, internalerror, virtual machine error, and a few others), but that's really an implementation detail. The point is: The gazillion different instances of 'handleWebRequest' are as simple as I could make them. NB: The db object isn't passed in primarily because not all these handlers need one, and the db engine is an entirely separate module, so I'd rather avoid adding a dependency there. If I didn't have lombok, I would make Db 'lazy' and grab a connection only when a request happens, so that you don't have to try/finally this stuff, and pass a Db object into the handleWebRequest call. For you JDBC users, I suggest you go play with projectlombok.org. Here's Christian Catchpole's code sample without lombok: PreparedStatement ps = connection.prepareStatement(sql); try { ResultSet resultSet = ps.executeQuery(); try { while (resultSet.next()) { // stuff } } finally { resultSet.close(); } } finally { ps.close(); } and here's the same thing with lombok: @Cleanup PreparedStatement ps = connection.prepareStatement (sql); @Cleanup ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { // stuff } If you have a need to handle SQLExceptions locally (I would like to state again that if you are forced to do this, your framework sucks and you should fix it!), it would turn into: try { @Cleanup PreparedStatement ps = connection.prepareStatement (sql); @Cleanup ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { // stuff }} catch ( SQLException e ) { //What are ya gonna do now? } rule of thumb: If you can't do anything useful in your catch block other than log and/or wrap it, you're doing it wrong. And to the genius who mentioned beep(): Whoa. Did not know about it. Evil! Muhahaha! On Aug 18, 3:29 am, phil swenson phil.swen...@gmail.com wrote: I'm happy to see all the runtime exception advocates on here. Definitely not the mainstream view. Smart crowd :) I would love to see some example of how you guys write JDBC code. JDBC code is usually the most heinous of all with all the SQLException and resource handling crap you have to do. Please post a snippet :) On Aug 17, 6:47 pm, Michael Neale michael.ne...@gmail.com wrote: The only sane way is this: try { .. your code here } catch (Throwable t) { for (int i =0; i 1000; i++) java.awt.Toolkit.beep(); System.exit(-1); } Sometimes can use a Runtime.exec to delete the home directory for good measure, but that means platform specific code. On Aug 18, 8:58 am, Casper Bang casper.b...@gmail.com wrote: For that we have Runtime().getRuntime().addShutdownHook() no? That's what I used anyway with JSR-296, where Hans Muller had hardwired the System.exit() call in the framework. /Casper On 17 Aug., 23:11, Peter Becker peter.becker...@gmail.com wrote: Jess Holle wrote: Peter Becker wrote: While I agree that you can have shared state, the scenario I had was a clean worker: some data goes in before the thread gets started, other data comes out at the end. System.exit is a bad idea generally since you don't really know who is going to use your code in the future. If you call System.exit in your average Tomcat installation you'll probably take it down with you. I tend to restrict the System.exit calls to
[The Java Posse] Re: How do YOU handle Exceptions?
Exceptions aren't just for exceptional situations. This seems perfectly legit to me: public class BankAccount { public void transferFundsTo(BankAccount other, int amount) throws InsufficientBalanceException {} } The InsufficientBalanceException is not an exceptional situation. It happens all the time, it's an intrinsic part of the design process. It's exceedingly likely the calling code will need to deal with the SITUATION that the bank account has insufficient funds. However, if this method just returned a boolean, they might forget to check. Proper usage of checked exceptions is actually that the exceptional cases (IOException, SQLException...), AND cases where the condition isn't particularly exceptional, but it is extremely unlikely that your average caller can do anything about it, you ought to be using runtimeexception (that would be the vast majority of them). For conditions that are NOT exceptional, you should be using checked exceptions. Of course, one mans exceptional usecase is another mans alternate exit condition, so this is fuzzy logic at best. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Reinier Zwitserloot wrote: Concrete examples: Runnable does not let you throw Exceptions. Anyone up for defending this grievous API design? The amount of annoyance that this is caused me is almost limitless. Well Runnable is really for cases where run() should eat any exceptions other than things like VirtualMachineErrors -- and should not be used for anything else. That said, this is exactly where BGGA's exception transparency should come into play -- to allow you to define: public interface CallableT,E { public T call() throws E; } I will almost certainly get BGGA's proposed syntax muddled here, but the important thing here is that call() could throw a precise set of checked exceptions and this set would be bubbled up in generic algorithms (rather than Exception as in CallableT today), e.g. public T,E visit( CallableT,E visitor ) throws SQLException, E; or some such. The actual list of checked exceptions emanating from visit would be SQLException, IOException, MalformedURLException if E was IOException, MalformedURLException. One can still wrap the exception at any point along the way, of course, but one is not /forced /to arbitrarily do so at various points as one is today just because of the imprecision of a generic algorithm's declaration. -- Jess Holle --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
The way I normally think about it is, business exceptions are (usually) checked exceptions. Error conditions are RuntimeExceptions. -Mario. -- I want to change the world but they won't give me the source code. On Tue, Aug 18, 2009 at 19:56, Reinier Zwitserloot reini...@gmail.comwrote: Exceptions aren't just for exceptional situations. This seems perfectly legit to me: public class BankAccount { public void transferFundsTo(BankAccount other, int amount) throws InsufficientBalanceException {} } The InsufficientBalanceException is not an exceptional situation. It happens all the time, it's an intrinsic part of the design process. It's exceedingly likely the calling code will need to deal with the SITUATION that the bank account has insufficient funds. However, if this method just returned a boolean, they might forget to check. Proper usage of checked exceptions is actually that the exceptional cases (IOException, SQLException...), AND cases where the condition isn't particularly exceptional, but it is extremely unlikely that your average caller can do anything about it, you ought to be using runtimeexception (that would be the vast majority of them). For conditions that are NOT exceptional, you should be using checked exceptions. Of course, one mans exceptional usecase is another mans alternate exit condition, so this is fuzzy logic at best. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
BGGA's checked exception handling is extremely complex. I don't like it at all. I'd much rather have a closure proposal where a method that takes a closure that has tennant's correspondence principle is strictly enforced by the compiler to keep the closure stack-safe. In other words, legal operations are: 1. Running the closure, 2. Grabbing info off of the closure object (running its toString or some such) 3. passing it on to another method that accepts closures. You can't assign it to another variable, give it to a method that isn't designed with these restrictions in mind, assign it to a field, or letting it escape any other way. This is nice for checked exceptions, as you can just ignore them, it'll all sort itself out, but it's also nice because with that restriction, you'll never run into the situation that break / continue / return in the closure becomes meaningless (those 3 statements become meaningless if the stack is gone. The for loop you're trying to break out of is long gone, so, what exactly is break supposed to do? In BGGA you'd get a TransferException at runtime. Meh). If the compiler knows FOR SURE that a given closure is always run so that the stack as it was when you defined it exists, then there's no need for all the checked exception generics. Any exception you could legally throw at the point where you defined the closure is legal to throw in the closure. Example: Let's say that, purely for arguments sake, do as a keyword modifier of a parameter signals that it can be a closure, and that you can only make parameters that are SAMs (types that carry exactly 1 abstract method). Then you could write Collections.sort as: public class Collections { public static T void sort(ListT list, do Comparator? super T comparator) { //do your sort thing. } The compiler will then strictly enforce that the sort method doesn't allow the comparator reference to escape (for its function, there's no need for that. Contrast to e.g. TreeSet's (Comparator) constructor, where the comparator must be stored in a field in the treeset, which would count. You could not stick a 'do' in front of that, the compiler would refuse to compile that constructor). Then, you would be able to legally do this in your code: try { Collections.sort(someStringList, #(String a, String b) { new File (a).getCanonicalPath().compareTo(new File(b).getCanonicalPath()) }); } catch ( IOException e ) { //deal with exception. } Please don't get hung up on the syntax, consider it pseudocode. I'm trying to convey the idea that you're calling code that declares 'throws IOException' (getCanonicalPath does that) in a method (Comparator.compare) which doesn't even let you declare 'throws IOException'. The compiler will accept this because it knows, _FOR SURE_, that the closure is always run so that the stack is intact; in other words, if an IOException does occur, either something in the mechanics of Collections.sort handles it, or, if it falls through, the catch block here will handle it. There's no violation of the checked exception type system; you can't have an IOException in a place that isn't prepared to handle them. In BGGA, the mechanism by which the compiler ensures the checked exception type system is valid is entirely different: Collections.sort would have to be changed (which isn't possible, backwards compatibility being the holy grail that it is, so we'd need a sort2 method. Yich!) to accept a parameter 'E' which is the exception type (s) thrown by the code block. Because you can throw multiple things, BGGA has a special syntax for this: public static T, throws E void sort(ListT list, {T = int throws E} closure) throws E { /*sort method */ } Here the compiler just binds E to the appropriate exception type, and as a result, due to the 'throws E' on the sort method itself, this propagates out. Now, BGGA has added quite a bit of complexity to make this work: - you have this special 'throws E' syntax, which does a special thing: It will match multiple exception types. so, if you type throws IOException, SQLException, and you're implementing a method with 'throws E' where the E is also specified in the generics type var name as 'throws E', then E will be [IOException, SQLException], which is something new - having 1 generics letter mean 2 different types. - you need to have rather a lot of 'throws E' everywhere. In that sort line, you have 3 mentions: In the generics var name, in the function type, and in the method body. Theoretically it could be different, but that's the pattern in 95% of all cases: The closure can throw something, and the method, which operates on the closure, just wants these exceptions to fall right out. This notion I have of enforcing a closure to run inside stack is also present in BGGA; after the first prototype, BGGA's break/return/ continue transparency was considered unwieldy because those terms are meaningless if the stack is gone. Therefore, 2 closure types exist, differentiated
[The Java Posse] Re: How do YOU handle Exceptions?
On Tue, Aug 18, 2009 at 3:13 AM, Peter Becker peter.becker...@gmail.comwrote: What I would really like to see is a meet/or/disjunction/union operator in the type system, with a case-like construct to resolve the resulting types. Scala has two things that are halfway there (Either, case classes), but neither is the full monty. Few type systems have true union types. The algebraic data types of the ML and Haskell families, for instance, do not allow unioning of types without explicitly creating a new type with its own constructors. See Either which in Haskell looks like. data Either a b = Left a | Right b In Scala, Haskell, or SML Either is really just a way of faking union typing in a type system that doesn't do union typing. Java is actually very unusual in that the small bit of its type system devoted to exceptions basically has union types. If a method says it throws A,B,C then the union A,B,C forms a type and the type A,B is a subtype, the type A,B,C,D is a supertype. With regards to declared exceptions on methods Java is covariant. I know that's not how checked exceptions are normally presented, but that's how the type rules work. But then Java, as usual, isn't very regular about this union typing business. You can write Integer myFunction(File file) throws IOException, MyBusinessException {...} But if you try to make it first class with something like interface FunctionIn, Out, Exc { Out apply(In in) throws Exc; } You can't then write something like new FunctionFile, Integer, {IOException, MyBusinessException} {...} Your first class function has to pick one exception or declare that it throws a common supertype. Project Coin proposed the ability to catch mutliple exception types with one catch block. That can be seen as extending union typing just a touch further, but it still doesn't cover exception types as type parameters. It's not surprising to me at all that Java remains virtually the only language with checked exceptions. They might be a fine idea, but making them usable and consistent across the language is very tough business. Checked exceptions are what's called an effects system, which is a way to extend a type system so that functions describe effects they might have beyond computing a value. Creating an effects system that is usable and consistent across the language is very much ongoing research. See Disciple http://www.haskell.org/haskellwiki/DDC/EffectSystem, but I warn you it's not for the faint of heart. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
I'm slightly embarrassed to admit I'm a fan of http://bugs.sun.com/view_bug.do?bug_id=6534270 On Aug 15, 5:56 am, Jeff Grigg jeffgr...@charter.net wrote: I like the beauty and simplicity of completely empty catch blocks. ;- OK, some developers, to comply with corporate documentation standards, put comments there. ;- (Reality is that I'll usually wrap checked exceptions in RuntimeExceptions at a low level, and then catch Exception at the top level -- to log it and abort or retry the transaction or user action. There's a lot of really bad code out there that misuses exceptions and does exception handling cleanup wrong. It's a problem!!) --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
BGGA's exception transparency hinges on disjunctive types, of course... James Iry wrote: On Tue, Aug 18, 2009 at 3:13 AM, Peter Becker peter.becker.de http://peter.becker.de@gmail.com http://gmail.com wrote: What I would really like to see is a meet/or/disjunction/union operator in the type system, with a case-like construct to resolve the resulting types. Scala has two things that are halfway there (Either, case classes), but neither is the full monty. Few type systems have true union types. The algebraic data types of the ML and Haskell families, for instance, do not allow unioning of types without explicitly creating a new type with its own constructors. See Either which in Haskell looks like. data Either a b = Left a | Right b In Scala, Haskell, or SML Either is really just a way of faking union typing in a type system that doesn't do union typing. Java is actually very unusual in that the small bit of its type system devoted to exceptions basically has union types. If a method says it throws A,B,C then the union A,B,C forms a type and the type A,B is a subtype, the type A,B,C,D is a supertype. With regards to declared exceptions on methods Java is covariant. I know that's not how checked exceptions are normally presented, but that's how the type rules work. But then Java, as usual, isn't very regular about this union typing business. You can write Integer myFunction(File file) throws IOException, MyBusinessException {...} But if you try to make it first class with something like interface FunctionIn, Out, Exc { Out apply(In in) throws Exc; } You can't then write something like new FunctionFile, Integer, {IOException, MyBusinessException} {...} Your first class function has to pick one exception or declare that it throws a common supertype. Project Coin proposed the ability to catch mutliple exception types with one catch block. That can be seen as extending union typing just a touch further, but it still doesn't cover exception types as type parameters. It's not surprising to me at all that Java remains virtually the only language with checked exceptions. They might be a fine idea, but making them usable and consistent across the language is very tough business. Checked exceptions are what's called an effects system, which is a way to extend a type system so that functions describe effects they might have beyond computing a value. Creating an effects system that is usable and consistent across the language is very much ongoing research. See Disciple http://www.haskell.org/haskellwiki/DDC/EffectSystem, but I warn you it's not for the faint of heart. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Reinier Zwitserloot wrote: BGGA's checked exception handling is extremely complex. I don't like it at all. You can gripe about that, but it is the only thing that really makes a code block work normally. If you have something like: for ( ... ) { // some code that throw IOException } then you'd expect to have to catch IOException or declare throws IOException. If you don't have exception transparency, then when you use closures to do something like forEachWombat( ... ) { // do some stuff that throws IOException } You'd get totally different behavior -- which is *not* acceptable in my book. Exception transparency is complex in terms of implementation -- but rather simple in terms of usage. It's really a missing piece of Java generics and exception handling in Java as I see. As for Collections.sort() -- if you want this to allow throwing of checked exceptions from the Comparable then this is a dramatic change in the contract and, yes, Collections.sort() would have to be reimplemented. There's still a big different between public T foo() and public T foo() throws E -- the former is saying only serious unforeseen runtime exceptions could possibly occur in foo() -- that's the contract. That the Comparable contract and changing that is a big change. On the other hand, that's not to say that Callable wouldn't be a lot better as public T call() throws E than public T call() throws Exception. -- Jess Holle --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
According to Joshua Engel's Programming for the Java VM, that is not part of the verification algorithm. I had planned to do something similar in Kijaro, and instead have NetBeans issue warnings when neglecting to catch a checked exception - but I never really found out how to override NetBeans version of javac, I assume its the same problem Reinier struggles with for Lombok. /Casper On 19 Aug., 03:17, Christian Catchpole christ...@catchpole.net wrote: People have suggested similar keywords - I don't like the idea of wrapping in a RuntimeException, but as we know, checked exceptions are a figment of Java's imagination and are simply enforced by the compiler. Why not simply allow them to bubble up as their original exception, just remove the need for checking them. void thing() coverts IOException { } Does anyone know, if you were to remove the throws declarations from a method in a class, would the JVM still validate the class file, if the method was clearly throwing checked exceptions? I assume it would allow it. I guess this is how Scala works. On Aug 19, 11:06 am, Alex Buckley alex.buck...@sun.com wrote: I'm slightly embarrassed to admit I'm a fan ofhttp://bugs.sun.com/view_bug.do?bug_id=6534270 On Aug 15, 5:56 am, Jeff Grigg jeffgr...@charter.net wrote: I like the beauty and simplicity of completely empty catch blocks. ;- OK, some developers, to comply with corporate documentation standards, put comments there. ;- (Reality is that I'll usually wrap checked exceptions in RuntimeExceptions at a low level, and then catch Exception at the top level -- to log it and abort or retry the transaction or user action. There's a lot of really bad code out there that misuses exceptions and does exception handling cleanup wrong. It's a problem!!) --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
I really hate phrasing something like this as being a figment. That's like saying that short and char are figments of the JVM's imagination because it's all just bits. None-the-less, the answer is that checked exceptions are enforced by Java's static system and not by the JVM at all. So Scala, Groovy, JRuby, etc pretty much just ignore them. Reinier posted a very clever way to take advantage of the fact that casts to type parameters aren't checked to effectively cast away the checkedness of an exception without wrapping it, which I'll copy in case you can't find it public class Sneak { public static RuntimeException sneakyThrow(Throwable t) { Sneak.RuntimeExceptionsneakyThrow0(t); return null; } @SuppressWarnings(unchecked) private static T extends Throwable void sneakyThrow0(Throwable t) throws T { throw (T) t; } } It gets used like public class Test { public void test() { throw sneakyThrow(new IOException(this should be checked, but it's not!)); } public static void main(String[] args) { try { new Test().test(); } catch (Exception e) { e.printStackTrace(); } } } It is mildly annoying that you can't catch IOException here because Java says it can't possibly happen. Silly Java, we just pervted you so that it can! On Tue, Aug 18, 2009 at 6:17 PM, Christian Catchpole christ...@catchpole.net wrote: People have suggested similar keywords - I don't like the idea of wrapping in a RuntimeException, but as we know, checked exceptions are a figment of Java's imagination and are simply enforced by the compiler. Why not simply allow them to bubble up as their original exception, just remove the need for checking them. void thing() coverts IOException { } Does anyone know, if you were to remove the throws declarations from a method in a class, would the JVM still validate the class file, if the method was clearly throwing checked exceptions? I assume it would allow it. I guess this is how Scala works. On Aug 19, 11:06 am, Alex Buckley alex.buck...@sun.com wrote: I'm slightly embarrassed to admit I'm a fan ofhttp:// bugs.sun.com/view_bug.do?bug_id=6534270 On Aug 15, 5:56 am, Jeff Grigg jeffgr...@charter.net wrote: I like the beauty and simplicity of completely empty catch blocks. ;- OK, some developers, to comply with corporate documentation standards, put comments there. ;- (Reality is that I'll usually wrap checked exceptions in RuntimeExceptions at a low level, and then catch Exception at the top level -- to log it and abort or retry the transaction or user action. There's a lot of really bad code out there that misuses exceptions and does exception handling cleanup wrong. It's a problem!!) --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
On 19 Aug., 04:06, James Iry james...@gmail.com wrote: I really hate phrasing something like this as being a figment. That's like saying that short and char are figments of the JVM's imagination because it's all just bits. Yeah well, it depends how you look at it I suppose. I would also claim generics to be a figment of the JVM's imagination, since you can not implement ComparableInteger and ComparableBigInteger due to it being an emulated construct at the parser level. Other languages with real generics have no problem with that, in Java all of a sudden you are going to need anonymous inner classes as dispatch adapters. /Casper --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
I can think of a hack. But it's not a very nice one and probably has limited use. You compile with throws Exception on the method and then edit the method signature in the resulting byte code. Perhaps easier than hacking javac. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
On 19 Aug., 04:24, Christian Catchpole christ...@catchpole.net wrote: I can think of a hack. But it's not a very nice one and probably has limited use. You compile with throws Exception on the method and then edit the method signature in the resulting byte code. Perhaps easier than hacking javac. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Maybe is good if something may or may not be there such in a dictionary lookup. The element not being available is a normal occurrence in that case. In the case of errors it would hide what the actual error was. Peter Michael Neale wrote: Or Maybe - (in which case you don't care about the None case, you just need to handle it). On Aug 18, 6:43 pm, Peter Becker peter.becker...@gmail.com wrote: In Scala you get the Either type. That is superior for most cases where one might use checked exceptions in Java. I have used that style in Java, but you usually don't make friends with it. Peter Michael Neale wrote: What do people think of the scala approach of no checked exceptions - even checked exceptions are not treated specially by the constructor (personally, I like it). On Aug 18, 12:55 pm, Christian Catchpole christ...@catchpole.net wrote: No, i just let that go up. I really try to avoid the declare as null then set thingy. On Aug 18, 12:03 pm, Casper Bang casper.b...@gmail.com wrote: You neglect to handle the checked exception declared by prepareStatement no? PreparedStatement stmt = null; try{ stmt = connection.prepareStatement(sql); final ResultSet rs = stmt.executeQuery(); try{ while (rs.next()){ // Stuff... { } finally{ rs.close(); }} catch(SQLException e){ // Logging...} finally{ try{ stmt.close(); } catch(SQLException whoTheFuckCares){ }; } Really, how many other ways are there to do it I wonder now? (Apart from wrapping certain things, like the last try-catch clause in some general purpose closer util?). /Casper --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Reinier Zwitserloot wrote: Concrete examples: Runnable does not let you throw Exceptions. Anyone up for defending this grievous API design? The amount of annoyance that this is caused me is almost limitless. Where would that exception go? Servlets require you to wrap checked exceptions into a 'ServletException', which is almost as bad. *ANY* exception caused by a servlet is cause to log it and return 500. Why the heck do I need to wrap these things? Who is helped by that? Which code has become more readable because of that? It makes some sense to me. The servlet container cares only about the fact that the servlet failed, the question why is rather secondary on that level. You could also imagine that subtypes are used to distinguish the actual problem. If you just allow any exception to go through (e.g. by letting the methods throw Exception on the API level), programmers will forget to handle things they could handle. InputStream.close() throws IOException. Nuff said. That only proves that exceptions are used badly in the JDK. NumberFormatException is a likely scenario that the calling code can usually handle directly, yet its a runtime exception. Making the case that IOException ought to be a runtime exception is a lot harder to make, so this is quite inconsistent. I totally agree, not catching NumberFormatException is something I consider a code stink -- unless the parsed string is a constant it is probably wrong. If it is a constant it begs the question: Why?. new String(whatever, UTF-8); throws an UnsupportedEncodingException. The JVM Spec says that you aren't a JVM unless you support at least the basic set of charsets. UTF-8 is there. So is ISO-8859-1, and so is US-ASCII. Thus, that line ought to be throwing a VirtualMachineError if UTF-8 is not found. IMO there should be accessor methods for the common encodings. Again: bad API design in the JDK, which we all seem to agree upon. FilterInputStream and FilterOutputStream's methods throw IOException, but if I feed it a ByteArrayInputStream, or I let it filter into a ByteArrayOutputStream, then an IOException can never happen. Which could be solved by having safe and unsafe versions of the interface. Any attempt to use a closure (anonymous inner class literal) where the closure is handed off for immediate processing, right there on the spot, nevertheless does not inherit the checked exceptions that can legally be thrown on the declaration site. There are a number of interfaces which are clearly supposed to be used this way, but its impossible to get the API right for these things. This is why the BGGA proposal has a very awkward part in it do deal with this issue. Designing such interfaces with a 'throws Throwable' clause doesn't help; you need to repeat the clause (1) and it would mean that calling code has to now deal with all throwables. It's just a disaster. Here, imagine you want to sort-in-place a list of files depending on their canonical path: Collections.sort(listOfFileObjects, new ComparatorFile() { public int compare(File a, File b) { return a.getCanonicalPath().compareTo (b.getCanonicalPath()); }}); Except the above code won't fly; getCanonicalPath throws IOException. Even if I wrap this entire line in a try/catch block, that won't help. How's that for examples? A nice list of examples where checked exceptions don't work well in the JDK. The latter points to an issue between checked exceptions and closures in the Java context. Does that in any way imply that the idea of checked exceptions is bad in general or that it is impossible to use checked exceptions in a positive way in Java? I don't see that yet. Peter On Aug 18, 5:55 pm, Alexey inline_f...@yahoo.com wrote: On Aug 18, 11:03 am, Casper Bang casper.b...@gmail.com wrote: On 18 Aug., 16:51, Alexey Zinger inline_f...@yahoo.com wrote: Maybe what this discussion needs is some real-world anecdotes of checked vs unchecked exceptions in production environments and how they helped or not to save the day. I would think it's a fairly real-world anecdote how no other language following Java introduced checked exceptions. Also you will have a much easier job coming up with language guro's against them than for them I think. I'm not convinced of that. So far, most of the complaints come from people talking about the imposition checked exceptions create on the coder. There's grumbling of misuse and hiding of exceptions by improper logging or catching and ignoring, but not much in the way of real-world scenarios. Not saying those statements aren't grounded in reality, but let's throw out some concrete situations to dissect and see how they could have been helped. I'm not a fan of how checked exceptions are used in specific API, JSE included, but I'm not against the concept as a whole. Lately, I've been working almost exclusively on web projects,
[The Java Posse] Re: How do YOU handle Exceptions?
Let me just say that I fully agree with this post. I believe most people look at the way checked exceptions are used and since that is mostly bad they assume the whole idea is bad. Since I can think of nicer solutions with checked exceptions for pretty much everything people complain about I am not willing to follow their argument. But I suspect we would need a full library stack written with checked exceptions in a better manner to see if they can work. Peter Alexey wrote: On Aug 18, 11:03 am, Casper Bang casper.b...@gmail.com wrote: On 18 Aug., 16:51, Alexey Zinger inline_f...@yahoo.com wrote: Maybe what this discussion needs is some real-world anecdotes of checked vs unchecked exceptions in production environments and how they helped or not to save the day. I would think it's a fairly real-world anecdote how no other language following Java introduced checked exceptions. Also you will have a much easier job coming up with language guro's against them than for them I think. I'm not convinced of that. So far, most of the complaints come from people talking about the imposition checked exceptions create on the coder. There's grumbling of misuse and hiding of exceptions by improper logging or catching and ignoring, but not much in the way of real-world scenarios. Not saying those statements aren't grounded in reality, but let's throw out some concrete situations to dissect and see how they could have been helped. I'm not a fan of how checked exceptions are used in specific API, JSE included, but I'm not against the concept as a whole. Lately, I've been working almost exclusively on web projects, many of them using GWT. Some of those projects were started by my predecessor and, not to put the guy down, but there's some horrendous exception handling there. Lots of catch(Exception), inconsistent and often broken logging, and all sorts of nasties like that. Some of the scenarios that were very difficult to debug (and still are in some parts of the systems) are the ones, where there's use of a 3rd party Excel authoring library (jxl as I recall). Occasionally, the code comes across a situation that breaks certain assumptions (unexpected formatting, or the like) and those almost inevitably get buried in ignored exception catches. I never get proper time to go through it (not that I'm that excited to do it) and clean it up, and so time and again we bump into some new extravagant way the system breaks. Now, one would read this and say, Aha! -- if only there were no checked exceptions, your predecessor would have written his sloppy code in a way that would allow those to propagate to the top layer (servlet container) and you would have seen it in some log and probably on some screen. Indeed, some of those exceptions are of checked variety. However, the code was written in a manner that didn't stand a chance. He simply assumed there would be no erroneous situation and dealt wrote EVERYTHING (file IO, DB, parsing/formatting, etc.) under a single try block and figured he'd just log whatever was caught in one catch (reuse, right?). And in fact, there ARE plenty of ways to handle these situations based on whatever kind of exception might arise. For instance, multiple formats might be tried on a single value before giving up, whereas a general Excel file read exception is probably unrecoverable. And then there's the unintended catching of RuntimeException that's sprinkled around there that also just lumps lots of different situations into one try/catch. This one can't be fixed by killing off checked exceptions, obviously. Overall, much of the problems could have been avoided by a better internal API design, that would separate different layers of functionality into finer granularity and would make it clear to the developer how to handle each and every exceptional situation differently, while still cleaning up resources when possible. So I don't think simply eliminating checked exceptions would have been the answer. I think both checked and unchecked have their place. Remember, that just because Java is the only language with checked exceptions, doesn't mean that it's a dead end. I do think that real world implementations have scared some people off the idea. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
phil swenson wrote: [...] Another issue I didn't mention is checked exceptions pollute the interface. Lets say you have a public API (interface) and add a new exception type. This makes every consumer of your API's code break. This violates the concept of having an API contract. So with checked exceptions either you are forced to 1) violate the contract or 2) not throw the exception you want to throw and wrap it in an unsuitable exception or 3) use a runtime exception. 3 is best:) So you are saying it is better to quietly change behaviour than to make a change to an API that breaks source compatibility? I certainly would not agree to that. people are so concerned with not knowing what exceptions are thrown, but if you test your projects you will discover when there are exceptions that are thrown and you want to handle. It's a rare occurrence. usually there is nothing you can do about it, so knowing that it will be thrown doesn't really help you out. I mean seriously, what do you do when you get a SQL Exception? it's almost always a bug. and a bug that might not be discovered if you used a checked exception and swallowed it. Sorry, but I call BS on that. SQLExceptions get thrown when the DB server is down or in trouble, when the network has issues and possibly other reasons that you do not encounter in test environments, so your testing won't help. Of course you can let it go through and just let your application provide with a generic error message, but there might be better ways of dealing with such an issue, in particular if the DB in question is not your only data source. For example: if your ads are served from a database and that is down, you probably want to fall back to some standard display, not a 500. Of course you could do that by catching Exception/Throwable around the component responsible, but the person integrating the system has to be aware that something can go wrong there. I guess you could just operate on the assumption that everything can fail and provide a generic error handler for each component, but I don't like this approach at all. In particular I believe that there should be parts of your code that do not throw exceptions at all. With checked exceptions you can distinguish the ones that do from the ones that don't. That approach just doesn't work well in Java because JDK libraries already throw a lot of Exceptions where they shouldn't (in particular the dreaded NPE). But that doesn't seem to allow concluding that the idea of checked exceptions is broken as such. Peter On Aug 18, 4:13 am, Peter Becker peter.becker...@gmail.com wrote: I still believe that the main reason people hate checked exceptions is that they have been used badly. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
I agree that there is a blurry line between exception and alternate return value and as stated elsewhere I would prefer a union type in most cases. In your example the exception should be reasonable exceptional, though -- after all people should not try a transfer unless they checked the balance first. I guess it all depends on how you define exceptional. Peter Reinier Zwitserloot wrote: Exceptions aren't just for exceptional situations. This seems perfectly legit to me: public class BankAccount { public void transferFundsTo(BankAccount other, int amount) throws InsufficientBalanceException {} } The InsufficientBalanceException is not an exceptional situation. It happens all the time, it's an intrinsic part of the design process. It's exceedingly likely the calling code will need to deal with the SITUATION that the bank account has insufficient funds. However, if this method just returned a boolean, they might forget to check. Proper usage of checked exceptions is actually that the exceptional cases (IOException, SQLException...), AND cases where the condition isn't particularly exceptional, but it is extremely unlikely that your average caller can do anything about it, you ought to be using runtimeexception (that would be the vast majority of them). For conditions that are NOT exceptional, you should be using checked exceptions. Of course, one mans exceptional usecase is another mans alternate exit condition, so this is fuzzy logic at best. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
On Tue, Aug 18, 2009 at 7:11 PM, Casper Bang casper.b...@gmail.com wrote: Yeah well, it depends how you look at it I suppose. I would also claim generics to be a figment of the JVM's imagination, since you can not implement ComparableInteger and ComparableBigInteger due to it being an emulated construct at the parser level. Well, not parser - type checker. But I know what you mean. Still, Haskell has a construct called newtype which creates a type whose representation is exactly the same as another type, but that the type system treats as compeltely different. That might allow you to say that inches are a type distinct from centimeters even though they are both represented with rational numbers. The fact that newtypes are guaranteed to be erased for efficiency's sake doesn't make them any more figmentary than any other type. Other languages with real generics have no problem with that, in Java all of a sudden you are going to need anonymous inner classes as dispatch adapters. Other languages...real generics. C++ of course uses templating to do polyinstantiation (ListFoo is a different class from ListBar) and mangles the hell out of names so you'd end up with compare_$_Integer and compare_$_BigInteger functions (or whatever your compiler does with them). That's all well and good as long as you stick to the same C++ compiler. But try to interop with another C++ compiler or another language like C and you suddenly start wishing all that type information would be erased. It also makes it damn hard to extend C++ with something like Java's wildcards or Scala's existintials and definition site variance. On the JVM side, Groovy has no problem consuming Java even though parameterized types are way beyond it, just try creating a dynamic language that so seamlessly interops with C++. So, point 1: erasure aids in interop and flexibility. In Haskell implementations are pretty free to do what they want but they tend to erase most types, except perhaps in distinguishing what Java people would call primitives. Haskell allows overloading but does it through a mechanism called a type class which is usually (though not always) implemented with dictionary passing (you can think of this as being somewhat like passing around a strategy object...sorta). So, point 2: different language semantics make erasure more palatable, and in Java different programming styles make it more or less palatable. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
Well actually, Stephen Colebourne has made is real easy to hack on the Java compiler - especially small hacks strictly at the parser level, which we're talking about here. If you want to try it check out a branch of Kijaro, locate the Check.java class and the methods matching the signatures: boolean isUnchecked(ClassSymbol exc) boolean isUnchecked(Type exc) Short circuit these by always returning true and... voila, no more checked exceptions. /Casper On 19 Aug., 04:24, Christian Catchpole christ...@catchpole.net wrote: I can think of a hack. But it's not a very nice one and probably has limited use. You compile with throws Exception on the method and then edit the method signature in the resulting byte code. Perhaps easier than hacking javac. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---
[The Java Posse] Re: How do YOU handle Exceptions?
especially small hacks strictly at the parser level Ok yeah, I know technically it's at the semantic analysis level, but I always think of the entire front-end (lexer, parser, semantic analysis) as just the parser. Somewhat simpler than optimizer and emitter. /Casper --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups The Java Posse group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~--~~~~--~~--~--~---