70 likes | 78 Views
Learn about how assertions can be used for debugging programs, the syntax for assert statements, and how to enable/disable assertions. Also, understand when to use assertions and when to use exceptions for error handling.
E N D
Assertions and Exception Handling CS-1020 Dr. Mark L. Hornick
Assertions can be used to help debug your programs • The syntax for the assert statement is assert( <boolean expression> ); • where <boolean expression> represents the condition that must be true if the code is working correctly. • If the expression is false, an AssertionError (a subclass of Error) is thrown. • You can’t (or shouldn’t) catch AssertionError’s CS-1020 Dr. Mark L. Hornick
Assert Example public double fromDollar(double dollar){ assert( exchangeRate > 0.0 ); // throw if <0 return (dollar * exchangeRate); } public double toDollar(double foreignMoney){ assert( exchangeRate > 0.0 );// throw if < 0 return (foreignMoney / exchangeRate); } CS-1020 Dr. Mark L. Hornick
The assert() statement may also take the form: assert(<boolean expr>): <expression>; • where <expression> represents the value passed as an argument to the constructor of the AssertionError class. • The value serves as the detailed message of a thrown error. CS-1020 Dr. Mark L. Hornick
Assertions Example public double fromDollar(double dollar){ assert exchangeRate > 0.0: “Exchange rate = “ + exchangeRate + “.\nIt must be a positive value.”; return (dollar * exchangeRate); } CS-1020 Dr. Mark L. Hornick
Assertions are normally disabled, and are usually only enabled for program testing • To run the program with assertions enabled, add the “-ea” argument to the VM in the Run Dialog • If the –ea option is not provided, the program is executed without checking assertions. CS-1020 Dr. Mark L. Hornick
Do not use the assertion feature to ensure the validity of an argument during normal execution Use assertions only to detect internal programming errors while debugging • Use exceptions during normal execution to notify client programmers of the misuse of classes. CS-1020 Dr. Mark L. Hornick