Monday, October 25, 2010

Project 12 Program Termination and Return Codes

For the project 12 subjects I will be comparing Java, C++ and Python. All being object oriented languages they share many things in common, but differ on several points as well.

All three of these languages provide exception statements (as discussed earlier). If the program runs into an error that is not handled by an exception, it will terminate. It is good to review code to make sure you have all possible exceptions handled. This way you prevent abnormal termination, although with larger programs it is difficult to place in an exception for every potential error the program may encounter during normal running.

Java provides a line to terminate the code, System.exit(int). The integer doesn't mean anything except for usage in debugging purposes. Typically, and it is considered good convention, a return of zero in there means you reached the end you hoped for, and a return of some other integer will let you know which exit it actually ended up getting to, one or two for instance (though in theory you could use any number, whichever number you as the programmer feel best represents what you want to convey via the exit).

In C++, it is possible to end a program or function prior to its normal termination by using an extra return 0; statement. This will end the entire program or function at that point, which may not always be what you had in mind so it should be used carefully. You can also use the exit(value) function, similar to Java's System.exit() command, this returns a value to the IDE that can than be used for error trapping.

Python is also has a similar ending command, sys.exit(value). Again used for the same thing as the C++ exit() function and Java System.exit() function. There are also a few other commands which you can use, such as raise SystemExit or just exit() though there are a few different things that they do and generally sys.exit is the preferred method to quit out of a program, since it is more "friendly" to other code. Good usage of this command will help during debugging if the program quits at certain times it normally shouldn't and returns a specific number, telling you why it quit.

The return command is also virtually identical through the three languages. Typically, it is used to end a function and return a particular value, be it a string, integer, double or anything else. It can also be used in C++ and Java by adding what is known as an "extra" return 0 command, which basically causes the same thing to happen as the standard exit commands for those languages. The break command, common to all three languages, can be used to quit out of a loop early instead of a return command, and is useful if the loop ends up going somewhere you didn't intend for it to go originally. It will not stop the external loop if you are using a nested loop, just the loop in which it has been places.

No comments:

Post a Comment