This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
The intention of using assertion is that the program should terminate as soon as the condition turns false, because it depicts a bug in the logic.
Thus "But why is it running" should n't get printed and that is what is achieved.
2) What happens when exception handling is used
We don't want the program to run further if i turns out to be zero,
however here the output is:
Should end here
But why is it running
Thus the purpose is not served, but what if i write something like this:
Here, as soon as it test that i is zero, it throws an exception to the calling method, which in turn throws it, thus a printStackTrace is generated, and "But why is it running" doesn't get printed
Thus the purpose is served by using exceptional handing(then why assertions?)
3)when if-else is used, what will happen:
We don't want the program to run further if the condition is not met, thus we don't want else to execute(because if it does, it will indicate a bug in the logic)
thus if else shouldn't be used. However, the following modification of if can serve the things:
/*We don't want program to run further if the value of i is 0" */
Output is :
Contion not met, program terminating...
When executed, the above program's execution terminates as soon as it reaches Line 01(Thus "But why is it running" doesn't get printed),
and a message is also generated which can be used for debugging,
Thus the purpose is served by using a modification of if(then why assertions?)
Joined: Dec 19, 2009
Considering the above usage of if and exception handling,
why are assertions used?
Joined: Dec 19, 2009
Help me out guys,,,,
why is everyone quiet?
Hello Ranch Hands, Henry you too, help me out yaar..........
Assertions are only meant while debugging code. They need to be explicitly enabled by using the -ea flag on the java command (i.e. java -ea). If they are not enabled, then the code will execute as if the line is not there. Your production code will most likely NOT be set to run in this mode. They are meant as a debug convience for the coder while developing.
Exception handling is meant to handle error conditions that may occur in the code in production. For example, you may get a FileNotFoundException when attempting to access a file on a network drive. You can choose to deal with this situation as appropriate by catching or throwing the exception.