When to use assert() and when to use try catch? - try-catch

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.

Related

The point of throwing exceptions

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.

Terminate activity diagram from subactivity

I´m trying to draw an UML activity diagram for a fnction that is (highly simplified) represented by the following code snippet. My intention is to have a subactivity for the lines that check the mode parameter (if-else).
ErrorType DoSomething(int mode) {
if(mode==MODE1) {
...
}
else {
return MODE_NOT_AVAILABLE;
}
SomethingElse...
return NO_ERROR;
}
You can see, the return-Statement in the else-Block leads to termination of function DoSomething. So if it´s executed, there is no way for SomethingElse... to be executed.
As I mentioned, this else-block should be in a subactivity.
How do I visualize that an action in a subactivity (return MODE_NOT_AVAILABLE) has the consequence that it´s parental activity diagram has to be in a final state?
In the following picture you can see my try to solve it. Is this a correct solution?
Since you are dealing with some kind of exception, I'd model it with an exception handler like you see here http://www.sparxsystems.com.au/images/screenshots/uml2_tutorial/ad11.GIF. Even though your concrete implementation uses if/else, that should be a way which makes it easy to understand what you want to achieve (prevent the subroutine from being executed in wrong mode).
You can see more details about the notation here: http://edn.embarcadero.com/article/30169
It depends on how much you want to dictate the actual implementation. UML itself is langage-unaware, and so are most stakeholders.

Is it a bad idea to mix bool and ret codes

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(...).

MSVS C# fastest way to remove try-catch blocks?

I took over an incomplete project and to my utter disbelieve, every single function is wrapped with try-catch statements in this same format:
try
{
// work work.
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, ...);
}
As I search SO for a method to quickly remove all these try-catch blocks, I find that people are actually looking for method to automatically wrap their functions with try-catch! hmmm... Is that good programming practice at all? Is there is method to remove all blocks instead so that it makes debugging easier and allows me to really solve the exceptions?
You can change the option here:
Debug -> Exceptions -> CLR Exceptions -> Check the "Thrown" checkbox.
This causes the compiler to break whenever an exception is thrown, before checking any catch blocks.
This is a horrible programming practice. I once saw this as a bug mess up someone's database.
It is my firm opinion you are better off letting your program die a fiery death than mindlessly continue on in an unknown state.
I would do a find and replace on MessageBox.Show(ex with throw //MessageBox.Show(ex and replace them all. You will have to manually find the ones that should really be there and put them back.
Visual Studio's Regex search is pretty powerful, however it is a bit tricky to use, here is something that you might find useful in searching for your above code: (Note in the find dialog box, in the Options section choose "Use: Regular Expressions")
Will find your bad catches:
catch.*\n+:b+{[.:b\n]MessageBox.[.:b\n]*}
If you want to do a straight replace with a throw:
catch\n{\nthrow;\n}
I've discovered a solution to this for VB.NET.
Replace this:
\s(?<!End )Try((.|\r\n)+?)Catch(.|\r\n)+?(Finally((.|\r\n)+?)End Try|End Try)
...with this:
$1$5
It will remove the entire try/catch block while leaving behind only what was in the try and finally blocks. It doesn't work with nested try/catches, though, so you'd need to replace the nested blocks first and then the outer blocks last.
Quick and dirty trick:
search & replace try -> if(true) //WAS TRY
search & replace catch§ -> if(true) //WAS CATCH §
§ is a placeholder for the regex to match what is catched and put it after the comment WAS CATCH
by this way you can:
revert searching WAS TRY and WAS CATCH §
decide what has to be replaced and what has not when during rhe search
I use to comment with // DUMMY every catch that is temporary during the debug session.
(since this is a very old post, I didn't take all the time needed to write the regex etc... please be patient)

How do I implement exceptions with nestable try-catch-finally statement with messages in C

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()

Resources