Is defining a "ProbableBugException" code smell, paranoia or good practice? - java

In my Java code, I occasionally run into situations where I have to catch a checked exception from a library function that I'm pretty sure can't occur in my use case.
Also, when coding, I sometimes notice that I'm relying on certain inputs from other modules (my own) to have or not have particular features. For example, I might expect a string to be in a certain format etc. In these situations, I would often put in a verification step, although I control the code that send the input myself.
At the moment, I'm working on a quite complex product that I want to be very reliable. Among other things, I want it to collect information from caught exceptions and automatically file bug reports. For the above two scenarios, I therefore defined an (unchecked) "ProbableBugException", that tells me I made a mistake in the code delivering the input data.
Is that a) stupid, b) paranoid or c) good practice? This is going to be subjective, I'll put up three wiki answers so we can vote away without rep warping.
ETA:
Thanks to Svend for pointing out that Java has assertions, I didn't realize that. Assertions are actuall pretty much what my question was about, but I only knew them from C and have never used them there.

I'm thinking that using an assert is what you really want there ("probably bug").

It's stupid, because:
the exception should be much more specific, like InvalidInputException
you should think harder about the input side, it's likely that it's shaky if you feel you need that kind of exception

It's good practice, because:
you might have a coworker coding on the input side and the two of you might have misunderstood each other
if you make a mistake, fixing it becomes trivial
in situations where the input side is a plugin of some sort, it helps the plugin developers (who might be external) to deliver correct input.

I always expect the unexecpected.
I often have code like this : ( $div will never be 0 into my code )
if( $div != 0 ) {
$var = $var2 / $div;
} else {
/*
* It should never happen
*/
throw Exception( 'relevant message' );
}
I always protect myself from me and the others

Related

Are Java streams meant only to be used for arrays? How about single elements?

I have been looking at Java streams and functional programming.
Figured a way to rewrite a small "user login" code.
Here is my login methods;
If the user from query is null, null pointer exception is handled on a filter.
public ResponseEntity login(User request) {
User dbUser = userRepo.findByEmail(request.getEmail());
if (!aes.matches(request.getPassword(), dbUser.getPassword()))
return ResponseEntity.status(403).build();
return logUserIn(dbUser);
}
private ResponseEntity logUserIn(User dbUser) {
dbUser.setPassword(null);
jwtHandler.setJwtCookie(dbUser);
return ResponseEntity.ok(dbUser);
}
And via using streams;
public ResponseEntity login(User request) {
return Stream.of(userRepo.findByEmail(request.getEmail()))
.filter(dbUser -> aes.matches(request.getPassword(), dbUser.getPassword()))
.map(this::logUserIn)
.findFirst()
.orElse(ResponseEntity.status(403).build());
}
private ResponseEntity logUserIn(User dbUser) {
dbUser.setPassword(null);
jwtHandler.setJwtCookie(dbUser);
return ResponseEntity.ok(dbUser);
}
I dont know if streams are meant to be used this way. Are they?
If i use similar kind of logic on more important parts of the project will I get in trouble later?
You might feel better about the if-else if you use it in a more functional style rather than short-circuiting:
if (!aes.matches(request.getPassword(), dbUser.getPassword())) {
return ResponseEntity.status(403).build();
}
else {
return logUserIn(dbUser);
}
Doing equivalent in one statement with Stream/Optional is harder to read and less performant.
You might consider the possibility of making findByEmail return Optional<User>, which is more idiomatic for any "find" method. Then you could combine the two approaches like
return userRepo.findByEmail(request.getEmail()).map(dbUser -> {
if (!aes.matches(request.getPassword(), dbUser.getPassword())) {
return ResponseEntity.status(403).build();
}
else {
return logUserIn(dbUser);
}
})... // .orElse(null) / .orElseThrow(...)
You'll get into trouble, mostly. The 'root' problem is that both ways of writing it are defensible as the 'best choice', and the java community, by and large, strongly prefers the second form. For the same reason it is a bad idea to name_variables_like_this (the community decided that the convention is to nameThemLikeThis). Breaking the mold will mean your code is harder to read by others and code written by others is harder to read for you. Also, you'll probably get friction when you try to interact with other code.
For example, right now (and for the foreseeable future), 'lambdas' (those things with the :: and the ->) are NOT exception transparent, NOT control flow transparent, and NOT mutable local variable transparent.
There are only 3 feasible options here:
Somehow write all code such that these 3 transparencies are never relevant regardless of what you're writing. That sounds impossible to me. Even if you somehow you manage, there are other libraries out there. Starting with java.*, which isn't designed for that kind of code style.
Mix code styles, going with lambda style when you don't immediately foresee the transparencies being relevant, otherwise going with the more imperative style if it is or you think it might be. This sounds silly to me; why mix 2 styles when a single style would have covered all the use cases?
Stick with lambda style, bending over backwards to account for the lack of these 3 transparencies where it bothers you, 'downgrading' variables to AtomicX variants, using such constructs to transmit exceptions and boolean flags to carry break and continue control flow outside, etectera. This is just writing ugly code just because you are particularly eneamoured of your fancy new shiny hammer and are just insisting on treating all problems as a nail, no?
That's.. trying to guess at what's going to happen when you interact with other code and other programmers. This snippet, in a vacuum, with just you? Eh, both work fine. Whatever you prefer, if community, friction with other code, and having a consistent style doesn't matter.
I have used Java 8 streams in live code and the biggest drawback for me is the stacktrace you get when an exception goes unhandled in the pipeline.
Sure they are nice to write and give you a sense of writing code in a functional style, but the truth is that streams are just a facade because underneath the fancy API, you are dealing with a monstrous abstraction layer over plain, ugly Java iterators, and this becomes painfully obvious when something goes awry such as an exception not being handled.
So the answer to your question is yes you might get in trouble, but it depends on how good you are at reading stacktraces, where 70% of the trace has nothing to do with code you've written but rather with the magic stuff used to turn iterators into streams.
As much as possible, prefer using if-else, for-loops, etc, unless you are confident that streams will be more efficient or easier to read. On that note, readability is quite important and part of the reason the Stream api exists is to improve readability, but moderation and good judgement are virtues worth exercising when making use of the full potential of the Streams API.

How does elm's compilation differ from Java's checked exceptions?

elm's claim of zero-runtime-exceptions is one of its major selling point (see official website),
But if you stop to think about it, nothing stops you from dividing by zero or running out of memory.
What the elm compiler basically does, is forcing you to cover all possible paths that can lead to an exception.
For example:
import String exposing (toInt)
toIntOrZero s = case toInt s of
Err e -> 0
Ok val -> val
But how does this differ from the infamous "checked-exceptions" feature in java ?
public static Integer toIntOrZero(String s) {
try { return Integer.valueOf(s); }
catch (NumberFormatException e) { return 0; }
}
I never heard any claims that java is a zero-runtime-exceptions language.
Please don't get too caught up on what is essentially marketing hyperbole. Of course there are classes of errors that you will never be able to fully rule out with any compiler.
As such, I've always taken these zero-runtime-exceptions claims with a grain of salt, but I think I understand the proponent's intent. Elm was created as an alternative to developing front-end applications in Javascript, which is a messy world where exceptions abound and are just part of everyday life. Elm makes it much harder to shoot yourself in the foot, and without too much effort, if you run through basic sanity testing on your app, you probably won't ever have runtime exceptions in production.
Elm drastically reduces the possibility of exceptions in a few ways.
There is no notion of a throwable exception in the language aside from Debug.crash, which, as its name implies, should really only be used for debugging and stubbing out incomplete logic paths.
Since there are no throwable exceptions, handling problems is most often done through types like Result and Maybe.
This could be thought of as loosely analagous to Java's checked exceptions but conceptually they feel very different than me. Let's face it. Exceptions have been abused. You mention an example in Java, where Integer.valueOf() says that it is going to return an int but if you pass it anything else, it unrolls the stack and bubbles up until some function hopefully catches it. This feels very messy to me, and sure, checked exceptions can aid in reducing the window for failure propagation, but the underlying fact is that an exception is the wrong tool for business logic.
An alternative to throwing an exception would be to have classes analagous to the Result and Maybe Elm types, but that would have been nearly impossible in the early days of Java to do cleanly, and even with Generics, writing such types is more tedious and error prone than the simplicity of Elm's types. And because of Elm's closed type system,
Non-exhaustive pattern matches cause a compilation failure
In Java and Javascript, there is no way to have exhaustive pattern match checking because the type system does not allow it. Sure, Typescript has introduced some functionality but you have to opt into it. In Elm, you have to explicitly handle all cases. Sure, I suppose you could argue that Elm let's you opt out of exhaustive pattern matching by ending all case statements with a catch-all _, but that would just be a silly abuse of the language. Those checks are there to help you, and I feel much safer with the fact that I don't get to opt-in to error checking in Elm - it's there by default!
Immutability
Immutability avoids loads of potential types of errors, too many to get into here.
The Elm Architecture offers a clean separation between Javascript and Elm
Elm compiles down to Javascript, but the Elm Architecture offers a nice clean barrier to keep all the nasty bits of Javascript away from the pure code written by Elm. Any exception that may happen in Javascript should be handled by that barrier, such that I/O errors will always be translated into an Elm-friendly, exceptionless type.
In the end, runtime exceptions are still possible (case in point: the next tagged Elm question dealt with a well-known runtime exception caused by a recursive JSON Decoder definition), and I cringe a little any time I hear someone say it's impossible to get an exception in Elm. The fact of the matter is that exceptions are possible, but nearly every exception you'd run across in day-to-day Javascript development is essentially impossible in Elm.
As a commenter pointed out, Java has unchecked exceptions, so runtime errors do occur. Elm also has unchecked exceptions, for things like division by zero, but gets rid of the ones most commonly seen in practice. And as Chad's answer mentions, Elm's Maybe/Result types work quite differently in practice than Java's checked exceptions. An experienced Elm programmer would not write a function like toIntOrZero (and if they did, they would probably not use case ... of, preferring instead something like toIntOrZero = String.toInt >> Result.withDefault 0).
Chaining multiple operations together with Result.map, Result.andThen, and so on gives a very expressive way of handling error cases without forcing the programmer to get too deep in the weeds. For example, if we want to write a function that validates an ID by converting it to an Int, looking it up in some data structure (when it might not be there), and then verifying some property associated with that user, we can write something like this:
lookupUser : Int -> Result String User
lookupUser intId = ...
userInGoodStanding : User -> Bool
userInGoodStanding user = ...
isValidId : String -> Bool
isValidId id =
String.toInt id
|> Result.andThen lookupUser
|> Result.map userInGoodStanding
|> Result.withDefault False
This reads, "convert the ID to an int, then look up the associated user, then verify the user, and if anything failed, return False." Your mileage may vary, but once you get to used to it, I (and many Elm programmers, I think!) find this to be a really nice way of writing code robust to errors.

Is relying on custom exception types for flow control considered good practice? [duplicate]

To avoid all standard-answers I could have Googled on, I will provide an example you all can attack at will.
C# and Java (and too many others) have with plenty of types some of ‘overflow’ behaviour I don’t like at all (e.g type.MaxValue + type.SmallestValue == type.MinValue for example : int.MaxValue + 1 == int.MinValue).
But, seen my vicious nature, I’ll add some insult to this injury by expanding this behaviour to, let’s say an Overridden DateTime type. (I know DateTime is sealed in .NET, but for the sake of this example, I’m using a pseudo language that is exactly like C#, except for the fact that DateTime isn’t sealed).
The overridden Add method:
/// <summary>
/// Increments this date with a timespan, but loops when
/// the maximum value for datetime is exceeded.
/// </summary>
/// <param name="ts">The timespan to (try to) add</param>
/// <returns>The Date, incremented with the given timespan.
/// If DateTime.MaxValue is exceeded, the sum wil 'overflow' and
/// continue from DateTime.MinValue.
/// </returns>
public DateTime override Add(TimeSpan ts)
{
try
{
return base.Add(ts);
}
catch (ArgumentOutOfRangeException nb)
{
// calculate how much the MaxValue is exceeded
// regular program flow
TimeSpan saldo = ts - (base.MaxValue - this);
return DateTime.MinValue.Add(saldo)
}
catch(Exception anyOther)
{
// 'real' exception handling.
}
}
Of course an if could solve this just as easy, but the fact remains that I just fail to see why you couldn’t use exceptions (logically that is, I can see that when performance is an issue that in certain cases exceptions should be avoided).
I think in many cases they are more clear than if-structures and don’t break any contract the method is making.
IMHO the “Never use them for regular program flow” reaction everybody seems to have is not that well underbuild as the strength of that reaction can justify.
Or am I mistaken?
I've read other posts, dealing with all kind of special cases, but my point is there's nothing wrong with it if you are both:
Clear
Honour the contract of your method
Shoot me.
Have you ever tried to debug a program raising five exceptions per second in the normal course of operation ?
I have.
The program was quite complex (it was a distributed calculation server), and a slight modification at one side of the program could easily break something in a totally different place.
I wish I could just have launched the program and wait for exceptions to occur, but there were around 200 exceptions during the start-up in the normal course of operations
My point : if you use exceptions for normal situations, how do you locate unusual (ie exceptional) situations ?
Of course, there are other strong reasons not to use exceptions too much, especially performance-wise
Exceptions are basically non-local goto statements with all the consequences of the latter. Using exceptions for flow control violates a principle of least astonishment, make programs hard to read (remember that programs are written for programmers first).
Moreover, this is not what compiler vendors expect. They expect exceptions to be thrown rarely, and they usually let the throw code be quite inefficient. Throwing exceptions is one of the most expensive operations in .NET.
However, some languages (notably Python) use exceptions as flow-control constructs. For example, iterators raise a StopIteration exception if there are no further items. Even standard language constructs (such as for) rely on this.
My rule of thumb is:
If you can do anything to recover from an error, catch exceptions
If the error is a very common one (eg. user tried to log in with the wrong password), use returnvalues
If you can't do anything to recover from an error, leave it uncaught (Or catch it in your main-catcher to do some semi-graceful shutdown of the application)
The problem I see with exceptions is from a purely syntax point of view (I'm pretty sure the perfomance overhead is minimal). I don't like try-blocks all over the place.
Take this example:
try
{
DoSomeMethod(); //Can throw Exception1
DoSomeOtherMethod(); //Can throw Exception1 and Exception2
}
catch(Exception1)
{
//Okay something messed up, but is it SomeMethod or SomeOtherMethod?
}
.. Another example could be when you need to assign something to a handle using a factory, and that factory could throw an exception:
Class1 myInstance;
try
{
myInstance = Class1Factory.Build();
}
catch(SomeException)
{
// Couldn't instantiate class, do something else..
}
myInstance.BestMethodEver(); // Will throw a compile-time error, saying that myInstance is uninitalized, which it potentially is.. :(
Soo, personally, I think you should keep exceptions for rare error-conditions (out of memory etc.) and use returnvalues (valueclasses, structs or enums) to do your error checking instead.
Hope I understood your question correct :)
A first reaction to a lot of answers :
you're writing for the programmers and the principle of least astonishment
Of course! But an if just isnot more clear all the time.
It shouldn't be astonishing eg : divide (1/x) catch (divisionByZero) is more clear than any if to me (at Conrad and others) . The fact this kind of programming isn't expected is purely conventional, and indeed, still relevant. Maybe in my example an if would be clearer.
But DivisionByZero and FileNotFound for that matter are clearer than ifs.
Of course if it's less performant and needed a zillion time per sec, you should of course avoid it, but still i haven't read any good reason to avoid the overal design.
As far as the principle of least astonishment goes : there's a danger of circular reasoning here : suppose a whole community uses a bad design, this design will become expected! Therefore the principle cannot be a grail and should be concidered carefully.
exceptions for normal situations, how do you locate unusual (ie exceptional) situations ?
In many reactions sth. like this shines trough. Just catch them, no? Your method should be clear, well documented, and hounouring it's contract. I don't get that question I must admit.
Debugging on all exceptions : the same, that's just done sometimes because the design not to use exceptions is common. My question was : why is it common in the first place?
Before exceptions, in C, there were setjmp and longjmp that could be used to accomplish a similar unrolling of the stack frame.
Then the same construct was given a name: "Exception". And most of the answers rely on the meaning of this name to argue about its usage, claiming that exceptions are intended to be used in exceptional conditions. That was never the intent in the original longjmp. There were just situations where you needed to break control flow across many stack frames.
Exceptions are slightly more general in that you can use them within the same stack frame too. This raises analogies with goto that I believe are wrong. Gotos are a tightly coupled pair (and so are setjmp and longjmp). Exceptions follow a loosely coupled publish/subscribe that is much cleaner! Therefore using them within the same stack frame is hardly the same thing as using gotos.
The third source of confusion relates to whether they are checked or unchecked exceptions. Of course, unchecked exceptions seem particularly awful to use for control flow and perhaps a lot of other things.
Checked exceptions however are great for control flow, once you get over all the Victorian hangups and live a little.
My favorite usage is a sequence of throw new Success() in a long fragment of code that tries one thing after the other until it finds what it is looking for. Each thing -- each piece of logic -- may have arbritrary nesting so break's are out as also any kind of condition tests. The if-else pattern is brittle. If I edit out an else or mess up the syntax in some other way, then there is a hairy bug.
Using throw new Success() linearizes the code flow. I use locally defined Success classes -- checked of course -- so that if I forget to catch it the code won't compile. And I don't catch another method's Successes.
Sometimes my code checks for one thing after the other and only succeeds if everything is OK. In this case I have a similar linearization using throw new Failure().
Using a separate function messes with the natural level of compartmentalization. So the return solution is not optimal. I prefer to have a page or two of code in one place for cognitive reasons. I don't believe in ultra-finely divided code.
What JVMs or compilers do is less relevant to me unless there is a hotspot. I cannot believe there is any fundamental reason for compilers to not detect locally thrown and caught Exceptions and simply treat them as very efficient gotos at the machine code level.
As far as using them across functions for control flow -- i. e. for common cases rather than exceptional ones -- I cannot see how they would be less efficient than multiple break, condition tests, returns to wade through three stack frames as opposed to just restore the stack pointer.
I personally do not use the pattern across stack frames and I can see how it would require design sophistication to do so elegantly. But used sparingly it should be fine.
Lastly, regarding surprising virgin programmers, it is not a compelling reason. If you gently introduce them to the practice, they will learn to love it. I remember C++ used to surprise and scare the heck out of C programmers.
The standard anwser is that exceptions are not regular and should be used in exceptional cases.
One reason, which is important to me, is that when I read a try-catch control structure in a software I maintain or debug, I try to find out why the original coder used an exception handling instead of an if-else structure. And I expect to find a good answer.
Remember that you write code not only for the computer but also for other coders. There is a semantic associated to an exception handler that you cannot throw away just because the machine doesn't mind.
Josh Bloch deals with this topic extensively in Effective Java. His suggestions are illuminating and should apply to .NET as well (except for the details).
In particular, exceptions should be used for exceptional circumstances. The reasons for this are usability-related, mainly. For a given method to be maximally usable, its input and output conditions should be maximally constrained.
For example, the second method is easier to use than the first:
/**
* Adds two positive numbers.
*
* #param addend1 greater than zero
* #param addend2 greater than zero
* #throws AdditionException if addend1 or addend2 is less than or equal to zero
*/
int addPositiveNumbers(int addend1, int addend2) throws AdditionException{
if( addend1 <= 0 ){
throw new AdditionException("addend1 is <= 0");
}
else if( addend2 <= 0 ){
throw new AdditionException("addend2 is <= 0");
}
return addend1 + addend2;
}
/**
* Adds two positive numbers.
*
* #param addend1 greater than zero
* #param addend2 greater than zero
*/
public int addPositiveNumbers(int addend1, int addend2) {
if( addend1 <= 0 ){
throw new IllegalArgumentException("addend1 is <= 0");
}
else if( addend2 <= 0 ){
throw new IllegalArgumentException("addend2 is <= 0");
}
return addend1 + addend2;
}
In either case, you need to check to make sure that the caller is using your API appropriately. But in the second case, you require it (implicitly). The soft Exceptions will still be thrown if the user didn't read the javadoc, but:
You don't need to document it.
You don't need to test for it (depending upon how aggresive your
unit testing strategy is).
You don't require the caller to handle three use cases.
The ground-level point is that Exceptions should not be used as return codes, largely because you've complicated not only YOUR API, but the caller's API as well.
Doing the right thing comes at a cost, of course. The cost is that everyone needs to understand that they need to read and follow the documentation. Hopefully that is the case anyway.
How about performance? While load testing a .NET web app we topped out at 100 simulated users per web server until we fixed a commonly-occuring exception and that number increased to 500 users.
I think that you can use Exceptions for flow control. There is, however, a flipside of this technique. Creating Exceptions is a costly thing, because they have to create a stack trace. So if you want to use Exceptions more often than for just signalling an exceptional situation you have to make sure that building the stack traces doesn't negatively influence your performance.
The best way to cut down the cost of creating exceptions is to override the fillInStackTrace() method like this:
public Throwable fillInStackTrace() { return this; }
Such an exception will have no stacktraces filled in.
Here are best practices I described in my blog post:
Throw an exception to state an unexpected situation in your software.
Use return values for input validation.
If you know how to deal with exceptions a library throws, catch them at the lowest level possible.
If you have an unexpected exception, discard current operation completely. Don’t pretend you know how to deal with them.
I don't really see how you're controlling program flow in the code you cited. You'll never see another exception besides the ArgumentOutOfRange exception. (So your second catch clause will never be hit). All you're doing is using an extremely costly throw to mimic an if statement.
Also you aren't performing the more sinister of operations where you just throw an exception purely for it to be caught somewhere else to perform flow control. You're actually handling an exceptional case.
Apart from the reasons stated, one reason not to use exceptions for flow control is that it can greatly complicate the debugging process.
For example, when I'm trying to track down a bug in VS I'll typically turn on "break on all exceptions". If you're using exceptions for flow control then I'm going to be breaking in the debugger on a regular basis and will have to keep ignoring these non-exceptional exceptions until I get to the real problem. This is likely to drive someone mad!!
Lets assume you have a method that does some calculations. There are many input parameters it has to validate, then to return a number greater then 0.
Using return values to signal validation error, it's simple: if method returned a number lesser then 0, an error occured. How to tell then which parameter didn't validate?
I remember from my C days a lot of functions returned error codes like this:
-1 - x lesser then MinX
-2 - x greater then MaxX
-3 - y lesser then MinY
etc.
Is it really less readable then throwing and catching an exception?
Because the code is hard to read, you may have troubles debugging it, you will introduce new bugs when fixing bugs after a long time, it is more expensive in terms of resources and time, and it annoys you if you are debugging your code and the debugger halts on the occurence of every exception ;)
If you are using exception handlers for control flow, you are being too general and lazy. As someone else mentioned, you know something happened if you are handling processing in the handler, but what exactly? Essentially you are using the exception for an else statement, if you are using it for control flow.
If you don't know what possible state could occur, then you can use an exception handler for unexpected states, for example when you have to use a third-party library, or you have to catch everything in the UI to show a nice error message and log the exception.
However, if you do know what might go wrong, and you don't put an if statement or something to check for it, then you are just being lazy. Allowing the exception handler to be the catch-all for stuff you know could happen is lazy, and it will come back to haunt you later, because you will be trying to fix a situation in your exception handler based on a possibly false assumption.
If you put logic in your exception handler to determine what exactly happened, then you would be quite stupid for not putting that logic inside the try block.
Exception handlers are the last resort, for when you run out of ideas/ways to stop something from going wrong, or things are beyond your ability to control. Like, the server is down and times out and you can't prevent that exception from being thrown.
Finally, having all the checks done up front shows what you know or expect will occur and makes it explicit. Code should be clear in intent. What would you rather read?
You can use a hammer's claw to turn a screw, just like you can use exceptions for control flow. That doesn't mean it is the intended usage of the feature. The if statement expresses conditions, whose intended usage is controlling flow.
If you are using a feature in an unintended way while choosing to not use the feature designed for that purpose, there will be an associated cost. In this case, clarity and performance suffer for no real added value. What does using exceptions buy you over the widely-accepted if statement?
Said another way: just because you can doesn't mean you should.
As others have mentioned numerously, the principle of least astonishment will forbid that you use exceptions excessively for control flow only purposes. On the other hand, no rule is 100% correct, and there are always those cases where an exception is "just the right tool" - much like goto itself, by the way, which ships in the form of break and continue in languages like Java, which are often the perfect way to jump out of heavily nested loops, which aren't always avoidable.
The following blog post explains a rather complex but also rather interesting use-case for a non-local ControlFlowException:
http://blog.jooq.org/2013/04/28/rare-uses-of-a-controlflowexception
It explains how inside of jOOQ (a SQL abstraction library for Java), such exceptions are occasionally used to abort the SQL rendering process early when some "rare" condition is met.
Examples of such conditions are:
Too many bind values are encountered. Some databases do not support arbitrary numbers of bind values in their SQL statements (SQLite: 999, Ingres 10.1.0: 1024, Sybase ASE 15.5: 2000, SQL Server 2008: 2100). In those cases, jOOQ aborts the SQL rendering phase and re-renders the SQL statement with inlined bind values. Example:
// Pseudo-code attaching a "handler" that will
// abort query rendering once the maximum number
// of bind values was exceeded:
context.attachBindValueCounter();
String sql;
try {
// In most cases, this will succeed:
sql = query.render();
}
catch (ReRenderWithInlinedVariables e) {
sql = query.renderWithInlinedBindValues();
}
If we explicitly extracted the bind values from the query AST to count them every time, we'd waste valuable CPU cycles for those 99.9% of the queries that don't suffer from this problem.
Some logic is available only indirectly via an API that we want to execute only "partially". The UpdatableRecord.store() method generates an INSERT or UPDATE statement, depending on the Record's internal flags. From the "outside", we don't know what kind of logic is contained in store() (e.g. optimistic locking, event listener handling, etc.) so we don't want to repeat that logic when we store several records in a batch statement, where we'd like to have store() only generate the SQL statement, not actually execute it. Example:
// Pseudo-code attaching a "handler" that will
// prevent query execution and throw exceptions
// instead:
context.attachQueryCollector();
// Collect the SQL for every store operation
for (int i = 0; i < records.length; i++) {
try {
records[i].store();
}
// The attached handler will result in this
// exception being thrown rather than actually
// storing records to the database
catch (QueryCollectorException e) {
// The exception is thrown after the rendered
// SQL statement is available
queries.add(e.query());
}
}
If we had externalised the store() logic into "re-usable" API that can be customised to optionally not execute the SQL, we'd be looking into creating a rather hard to maintain, hardly re-usable API.
Conclusion
In essence, our usage of these non-local gotos is just along the lines of what [Mason Wheeler][5] said in his answer:
"I just encountered a situation that I cannot deal with properly at this point, because I don't have enough context to handle it, but the routine that called me (or something further up the call stack) ought to know how to handle it."
Both usages of ControlFlowExceptions were rather easy to implement compared to their alternatives, allowing us to reuse a wide range of logic without refactoring it out of the relevant internals.
But the feeling of this being a bit of a surprise to future maintainers remains. The code feels rather delicate and while it was the right choice in this case, we'd always prefer not to use exceptions for local control flow, where it is easy to avoid using ordinary branching through if - else.
Typically there is nothing wrong, per se, with handling an exception at a low level. An exception IS a valid message that provides a lot of detail for why an operation cannot be performed. And if you can handle it, you ought to.
In general if you know there is a high probability of failure that you can check for... you should do the check... i.e. if(obj != null) obj.method()
In your case, i'm not familiar enough with the C# library to know if date time has an easy way to check whether a timestamp is out of bounds. If it does, just call if(.isvalid(ts))
otherwise your code is basically fine.
So, basically it comes down to whichever way creates cleaner code... if the operation to guard against an expected exception is more complex than just handling the exception; than you have my permission to handle the exception instead of creating complex guards everywhere.
You might be interested in having a look at Common Lisp's condition system which is a sort of generalization of exceptions done right. Because you can unwind the stack or not in a controlled way, you get "restarts" as well, which are extremely handy.
This doesn't have anything much to do with best practices in other languages, but it shows you what can be done with some design thought in (roughly) the direction you are thinking of.
Of course there are still performance considerations if you're bouncing up and down the stack like a yo-yo, but it's a much more general idea than "oh crap, lets bail" kind of approach that most catch/throw exception systems embody.
I don't think there is anything wrong with using Exceptions for flow-control. Exceptions are somewhat similar to continuations and in statically typed languages, Exceptions are more powerful than continuations, so, if you need continuations but your language doesn't have them, you can use Exceptions to implement them.
Well, actually, if you need continuations and your language doesn't have them, you chose the wrong language and you should rather be using a different one. But sometimes you don't have a choice: client-side web programming is the prime example – there's just no way to get around JavaScript.
An example: Microsoft Volta is a project to allow writing web applications in straight-forward .NET, and let the framework take care of figuring out which bits need to run where. One consequence of this is that Volta needs to be able to compile CIL to JavaScript, so that you can run code on the client. However, there is a problem: .NET has multithreading, JavaScript doesn't. So, Volta implements continuations in JavaScript using JavaScript Exceptions, then implements .NET Threads using those continuations. That way, Volta applications that use threads can be compiled to run in an unmodified browser – no Silverlight needed.
But you won't always know what happens in the Method/s that you call. You won't know exactly where the exception was thrown. Without examining the exception object in greater detail....
I feel that there is nothing wrong with your example. On the contrary, it would be a sin to ignore the exception thrown by the called function.
In the JVM, throwing an exception is not that expensive, only creating the exception with new xyzException(...), because the latter involves a stack walk. So if you have some exceptions created in advance, you may throw them many times without costs. Of course, this way you can't pass data along with the exception, but I think that is a bad thing to do anyway.
There are a few general mechanisms via which a language could allow for a method to exit without returning a value and unwind to the next "catch" block:
Have the method examine the stack frame to determine the call site, and use the metadata for the call site to find either information about a try block within the calling method, or the location where the calling method stored the address of its caller; in the latter situation, examine metadata for the caller's caller to determine in the same fashion as the immediate caller, repeating until one finds a try block or the stack is empty. This approach adds very little overhead to the no-exception case (it does preclude some optimizations) but is expensive when an exception occurs.
Have the method return a "hidden" flag which distinguishes a normal return from an exception, and have the caller check that flag and branch to an "exception" routine if it's set. This routine adds 1-2 instructions to the no-exception case, but relatively little overhead when an exception occurs.
Have the caller place exception-handling information or code at a fixed address relative to the stacked return address. For example, with the ARM, instead of using the instruction "BL subroutine", one could use the sequence:
adr lr,next_instr
b subroutine
b handle_exception
next_instr:
To exit normally, the subroutine would simply do bx lr or pop {pc}; in case of an abnormal exit, the subroutine would either subtract 4 from LR before performing the return or use sub lr,#4,pc (depending upon the ARM variation, execution mode, etc.) This approach will malfunction very badly if the caller is not designed to accommodate it.
A language or framework which uses checked exceptions might benefit from having those handled with a mechanism like #2 or #3 above, while unchecked exceptions are handled using #1. Although the implementation of checked exceptions in Java is rather nuisancesome, they would not be a bad concept if there were a means by which a call site could say, essentially, "This method is declared as throwing XX, but I don't expect it ever to do so; if it does, rethrow as an "unchecked" exception. In a framework where checked exceptions were handled in such fashion, they could be an effective means of flow control for things like parsing methods which in some contexts may have a high likelihood of failure, but where failure should return fundamentally different information than success. I'm unaware of any frameworks that use such a pattern, however. Instead, the more common pattern is to use the first approach above (minimal cost for the no-exception case, but high cost when exceptions are thrown) for all exceptions.
One aesthetic reason:
A try always comes with a catch, whereas an if doesn't have to come with an else.
if (PerformCheckSucceeded())
DoSomething();
With try/catch, it becomes much more verbose.
try
{
PerformCheckSucceeded();
DoSomething();
}
catch
{
}
That's 6 lines of code too many.

Where to catch and process null arguments?

When I code, I often ask myself the same question :
Do I have to verify all arguments are not null ? So, in each method, I will have something like that :
if (arg1 == null)
{
throw FooException("...");
}
if (arg2 == null)
{
throw FooException("...");
}
If not, in which case is preferable ?
What's the best practices ?
As always, it depends.
If you're writing an API to be used by other teams / organizations, such defensive programming with precondition checks on public functions can really help your users; when using an external library, a meaningful error message like 'argument passed to foo() should not be null' is way better than NullPointerException thrown from some inner class.
Outside of API, though, I think such checks clutter the code too much. Thrown NullPointerExceptions are usually pretty easy to trace with debugger anyway. In languages that support them, you can consider using assertions - their syntax is usually less cumbersome, and you can turn them off on production so the checks won't degrade performance.
Unfortunetly, yes. you should check all arguments. Now ideally, if you code with good design practices one function should not have more than 4 or 5 arguments, at the most.
Having said that, one should always check for null values in function entry and throw appropriate exception or IllegalArgumentException (my fav).
Furhter, one should never pass NULL to a function and should never return a NULL. Sounds simple but it will save lots of code and bugs. Have a look at the NULL Design Pattern too.
Depends, if you want different exceptions i guess you would have to do that for all occasions where you might get a null value. Another way would be to user DATATYP.TryParse(). Look that up.
Hope it helps.
Since you're throwing an exception anyway, not verifying them would probably just lead to a nullpointerexception or something similar. I'm not entirely sure what the best practices are myself.
You should ideally always verify any arguments before you perform any action that might modify any state or data associated with said arguments. It's better to fail early and in a manageable way (by throwing a exception) than to end up with an inconsistent state / data which then also has to be resolved.
Your methods are expecting certain data to be there, there are some cases when it should be safe to assume that it is actually there (say inside a private method, which is called from other methods which validate input). However in general I would recommend validating arguments whenever they are:
Supplied by a user.
Supplied as part of an API.
Passed between modules of a system .
It's might be worth taking a look at this previous StackOverflow question.
I feel it's mostly down to common sense, and a little down to personal preference.
As others have mentioned, if it's a public API then you want to provide clear error messages wherever possible, so it's best to check parameters before they are used and throw exceptions with messages as per your example.
If it's internal code then there are two other options to think about: use assertions, or don't bother with the validation and rely on debugging. As a rule of thumb, I'll put assertions in if it's code that I expect other developers will be calling or if the condition is subtle enough that debugging it might be a pain. Otherwise, I'll just allow it to fail.
Sometimes you can avoid the issue by using the Null Object pattern. If it's a public API I'd still be inclined to include the checks though.

How to predict at first look whether it will give a runtime error or will not compile

I am looking at quizzes and tests at various sites (like blackbeltfactory, etc..) about java. I come across with questions which have choices like "doesn't compile" or "throws exception at runtime".
Are there any way to guess which will occur, at first look? Or is it a matter of getting familiar with java?
I think this is an important point on how java works.
Thanks in advance,
Bugra
For a human, you have to "get familiar with Java".
For a machine ( or a program that is ) it has to follow the rules the language specifies.
For instance the given class:
class Main {
String s;
}
What would be the result of invoking:
Main m = new Main();
m.s.length();
A) doesn't compile?
B) throws exception at runtime?
To answer this specific question you have to know, how classes are defined in Java ( to know if the one I show is a valid class definition or not ) , also you have to know how attributes are defined and default values etc, so you have to get familiar with the language.
When you know all these concepts, you can easily answer with a quick view.
BTW, the famous Sun Certified Java Programmer certification, is all about know this kind of stuff, rather than knowing how to develop an application. It is about converting your self in a "human compiler"
Obviously, knowing Java better will help. However, there are some general rules.
"Doesn't compile" means that the compiler literally could not understand the syntax of the code. This can happen as the result of misplaced or missing brackets or parentheses, methods with the wrong number of arguments, and other such things:
int a = (3 + 2) - 1);
"Throws exception at runtime" means that the written code makes sense syntactically, but that when it is actually executed it tells the machine to do something that is, for whatever reason, impossible. some exceptions are built into the language, such as if you try to divide by zero, but many are also explicitly defined and thrown in the code. Programmers use such exceptions to create programs which visibly break when they try to do something they shouldn't, rather than breaking silently and then causing other problems down the road:
int a = b / c; // very bad if c == 0
Generally speaking, compiler errors will look more like typos (and often will result from typos), whereas runtime exceptions will result from lines which fail under specific conditions (e.g. some variable is equal to zero). Once again, though, there is no real substitute for truly knowing the language.
In my honest opinion is a matter of getting familiar with java but some compiling errors are clear at first sight and they are very similar to other languages.

Categories