1 / 7

Assertions

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.

reesehenry
Télécharger la présentation

Assertions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Assertions and Exception Handling CS-1020 Dr. Mark L. Hornick

  2. 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

  3. 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

  4. 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

  5. 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

  6. 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

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

More Related