What's the point of throwing exceptions?
For example I stumbled across this:
static List<Integer> list(int [] a) {
if (a == null)
throw new NullPointerException();
//...
But when you don't throw the nullpointer, you'll also get a nullpointer?
I see this regularly and I wanted to know if this is a good habit to learn?
It's better to fail fast. For example the function could do a bunch of stuff before it even references the variable "a" in your example resulting in a lot of unnecessary processing.. It would be best just to fail immediately if you know "a" is null from the very beginning. You could also append a custom error message to the exception as well.
The idea behind the THROW is to prevent the error from stopping your program.
If it's a fatal enough error, your program will stop anyway. But if the program can continue it will, and just let you know that an error occurred.
In many cases, you assign a function to report the error, since you threw it up and know what it is.
I always found throwing exceptions to be a matter of design and readability. For example, generally when I design something I prefer to handle errors where they occur. However an equally valid design would be to throw the exception and handle it somewhere else. I have seen some abstractions where generally your flow is something similar to this...
FlowControl -> GenericMethod(catches exceptions and calls methods only) -> PrivateMethods (generally used to do the work, throws exceptions).
You might find a more complete answer here as well: When to catch the Exception vs When to throw the Exceptions?
It's possible that the rest of your method will not throw the exception and will instead have some kind of undesirable behavior if you use a null pointer. In your example, if it's basically a "ToList" wrapper, it might be implemented as:
static List<Integer> list(int[] a)
{
List<int> ret = new List<int>();
foreach (int i in a)
ret.add(i);
return ret;
}
Instead of throwing, this will simply return an empty list (if I recall correctly at least, I don't think C# throws on null lists used in foreach). As such, you'll need to include an explicit null check and throw to get your desired behavior.
Throwing specific exception means that your application has faced something it shouldn't have. It can be either invalid argument(when someone passes null and current method cannot work with value of null), invalid field state(its value has been changed to some value, which is forbidden for instance current state) and many many more.
Basically when you throw exceptions in a good manner, each person using your e.g. library can preserve its correct flow.
Related
I've seen the Index.search method raise a search.TransientError, and I know other methods may raise such errors as well, but in the documentation, I'm seeing code like this:
# Index the document.
try:
index.put(doc)
except search.PutError, e:
result = e.results[0]
if result.code == search.OperationResult.TRANSIENT_ERROR:
# possibly retry indexing result.object_id
except search.Error, e:
# possibly log the failure
When are checks like this necessary, and in which cases can I rely on search.TransientErrorbeing raised?
Looking through the source code, it looks like some (if not all) methods of the Index class use the _MakeSyncSearchServiceCall function, which, if anything goes wrong, calls _ToSearchError passing in an exception. This error returns an element from the _ERROR_MAP dictionary, based on the application_error property of the error. This dictionary contains theTransientError`, so it is clear that it is raised in certain cases.
So, when is it necessary to check result.code, and what other errors could be raised in cases that are out of my control?
I found two lines in my code.
test = new qx.ui.form.RadioGroup;
I am wondering, if the missing () might cause issues or should maybe raise a warning in the generator or the lint job.
qx.ui.form.RadioGroup;
I think it might be worth reporting it as a "statement without effect" in lint.
mck89's comment is the answer (I wonder why so many people put valid answers in comments...):
You don't need the parens, and new qx.ui.form.RadioGroup is a syntactically correct expression, equivalent to adding a pair of empty parens. (There are some checkers that will warn about this, like I believe JsLint, but qooxdoo doesn't ... :).
In your particular case, the code will also run successfully in the browser, as RadioGroup permits empty constructor args; you can use .add() later to add items to the group.
I have some programs which make heavy use of libraries with enumerations of error codes.
The kind where 0(first value of enum) is success and 1 is failure. In some cases I have my own helper functions that return bool indicating error, in other cases I bubble up the error enumeration. Unfortunately sometimes I mistake one for the other and things fail.
What would you recommend? Am I missing some warnings on gcc which would warn in these cases?
P.S. it feels weird to return an error code which is totally unrelated to my code, although I guess I could return -1 or some other invalid value.
Is it a bad idea? No, you should do what makes sense rather than following some abstract rule (the likes of which almost never cater for all situations you're going to encounter anyway).
One way I avoid troubles is to ensure that all boolean-returning function read like proper English, examples being isEmpty(), userFlaggedExit() or hasContent(). This is distinct from my normal verb-noun constructs like updateTables(), deleteAccount() or crashProgram().
For a function which returns a boolean indicating success or failure of a function which would normally follow that verb-noun construct, I tend to use something like deleteAccountWorked() or successfulTableUpdate().
In all those boolean-returning cases, I can construct an easily readable if statement:
if (isEmpty (list)) ...
if (deleteAccountWorked (user)) ...
And so on.
For non-boolean-returning functions, I still follow the convention that 0 is okay and all other values are errors of some sort. The use of intelligent function names usually means it's obvious as to which is which.
But keep in mind, that's my solution. It may or may not work for other people.
In the parts of the application that you control, and the parts that make up your external API I would say, choose one type of error handling and stick to it. Which type is less important, but be consistent. Otherwise people working on your code will not know what to expect and even you yourself will scratch you head when you get back to the code in a year or so ;)
If standardizing on a zero == error scheme, you can mix and match both enum and bool if you construct your tests like this:
err = some_func();
if !err...
Since the first enum evaluates to zero and also the success case it matches perfectly with bool error returns.
However, in general it is better to return an int (or enum) since this allows for the expansion of the error codes returned without modification of calling code.
I wouldn't say, that it's a bad practice.
There's no need to create tons of enum-s, if you just need to return true/false, and you don't have other options (and true and false are explanatory enough ).
Also, if your functions are named OK, you will have less "mistakes"
For example - IsBlaBla - expects to return true. If you have [Do|On]Reload, a reload could fail for many reasons, so enum would be expected. The same for IsConnected and Connect, etc.
IMHO function naming helps here.
E.g. for functions that return a boolean value, is_foo_bar(...), or for functions that return success or an error code, do_foo_bar(...).
In which situations do you use them?
Try... catch - for exceptional conditions, i.e. conditions which aren't caused by malformed code, but which may just alter the normal control flow by external unpredictable events.
Assertions for catching invalid code, i.e. checking if an invariant is held in the function, checking if an internal method is called with right arguments (for public API you might still want an exception for that), etc.
Those are my basic guidelines, but the conventions vary from situation to situation and from language to language.
When you're in doubt, you can ask yourself: is that specific safety check supposed to still be there in the release code, after we test and finish everything? If you answer "yes, it's still neccessary then", you probably want an exception. Otherwise, you probably want an assertion.
Normally assert() does not work in release code, so it can never replace a try-catch strategy. Nevertheless I like to use assert() in places where exceptions are thrown. For me (as a developer!), it is often more convenient to get by an assert() message to the line of failure than through the exception stack.
They are created for different purposes. Assert is more for finding bugs, try-catch is for handling exceptional situations.
The situations of try-catch and assert are totally different.
Assert is used to check if the value you have received, as parameter for example, is expected. I would not recommend to use assert in production code, it is used in unit-test mostly and rarely to check the parameters.
To check the passed values better to use something like:
public void test(int i) {
if (i < 0) {
throw new IllegalArgumentException("i cannot be less than 0");
}
...
}
Try-catch block is used when you know something inside the block can go wrong. For example, you write to an sdcard and there is no space for writing. Or, it happened that you try to read the array out of it bounds. Then, you put your critical code in try-catch block and check for the excpetions:
try {
InputStream is = new FileInputStream("filename.txt");
...
} catch FileNotFoundExcpetion {
System.out.println("file not found");
} finally {
...
}
More about exceptions and try-catch blocks.
I'm looking to implement exceptions with nestable try-catch-finally statement with messages in C using longjmp/setjmp.
I've managed to implement try-catch-else exceptions, they are not nestable. I'm also hoping to add messages to the exceptions. Any idea how I might be able to do it?
Dave Hanson has already done a really nice package of exception macros as part of his excellent book C Interfaces and Implementations. You could either use the code wholesale or learn from his techniques. For anyone who does a fair amount of C programming, the book is worth buying—it will change the way you change about C programming, and it will show you how to do object-oriented design in C.
For nesting: a stack-frame of current try/catch blocks.
Your try will be using setjmp to save to a jmpbuffer (I guess). If you've done a try, and hence are now in the scope of a try block and hit another try then you want to preserve the existing jmpbuffer and also create a new one - Push - and when catching you are longjmp-ing back to the point of the most recent try hence you Pop the latest jmpbuffer. So I think a stack-like model make sense for nested try/catch.
For implementation, I guess the simplest apporach is to reserve an array of jmpbuffers, hence limiting your try catch depth - but keeping it simple; Push and Pop just require you to track the index in that array.
For messages and other exception contents, a reserved area for "currentException".
Exception content. Keep it simple, define an Exception struct. A char array and an int. Keeping it simple, but not too simple, reserve an array of them so that you can support chaining.
For a throw you allow
throw ( "string", errcode )
Which simply zeros the array structure and makes one entry. And
catch ( exception )
Now can look in the array and finds the first entry, and then
throwChain ( "string", errcode)
Which adds the new exception to the array (if there is room, and if not can shuffle the array according some rule such as FIFO)
But, I've got to ask, why not just use C++?
Well, you cannot really implement exceptions in C since they are not supported by the language. The best you can do is emulate them using setjmp and longjmp and some diabolically clever macros.
A quick search turns up these links that may be useful to you:
Exceptions in C
Exception handling with longjmp()