Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS-1020 and Exception Handling

Similar presentations


Presentation on theme: "CS-1020 and Exception Handling"— Presentation transcript:

1 CS-1020 and Exception Handling
5/15/2019 Assertions and Exception Handling Portions adapted with permission from the textbook author. CS-1020 Dr. Mark L. Hornick 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 Portions adapted with permission from the textbook author. 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); Portions adapted with permission from the textbook author. 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. Portions adapted with permission from the textbook author. 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); } Portions adapted with permission from the textbook author. 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. Portions adapted with permission from the textbook author. 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. Portions adapted with permission from the textbook author. CS-1020 Dr. Mark L. Hornick


Download ppt "CS-1020 and Exception Handling"

Similar presentations


Ads by Google