11-Jun-14 The assert statement. 2 About the assert statement The purpose of the assert statement is to give you a way to catch program errors early The.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

1. Define the concept of assertions. 1 Explain the use of assertions. 2 Create Java program using assertions. 3 Run Java program using assertions. 4 2.
Detecting Bugs Using Assertions Ben Scribner. Defining the Problem  Bugs exist  Unexpected errors happen Hardware failures Loss of data Data may exist.
1 CSE 403 Design by Contract Reading: Pragmatic Programmer Ch. 4, Object-Oriented Design and Patterns, Ch. 3 (Horstmann) These lecture slides are copyright.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Fall 2013 Chapter 13 Exception.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
8-May-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
Chapter 8 Designing Classes. Assignment Chapter 9 Review Exercises (Written)  R8.1 – 8.3, 8.5 – 8.7, 8. 10, 8.11, 8.13, 8.15, 8.19, 8.20 Due Friday,
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
The Java Assert Statement. 2 Assert A Java statement in JDK 1.4 & newer Intent: enables code to test assumptions. E.g., a method that calculates a particle’s.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
JUnit, Revisited 17-Apr-17.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Computer Science 340 Software Design & Testing Design By Contract.
Ranga Rodrigo. Class is central to object oriented programming.
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
Testing. What is Testing? Definition: exercising a program under controlled conditions and verifying the results Purpose is to detect program defects.
1 Chapter 18 Exception Handling. 2 Motivations F Program runs into a runtime error –program terminates abnormally F How can you handle the runtime error.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Assertions Program correctness. Assertions Java statement – enables you to assert an assumption about your program. – An assertion contains a Boolean.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Exception Handling.
Chapter 12: Exception Handling
Errors And How to Handle Them. GIGO There is a saying in computer science: “Garbage in, garbage out.” Is this true, or is it just an excuse for bad programming?
1 Assertions. 2 assertions communicate assumptions about the state of the program, and stop processing if they turn out to be false very often comments.
Exceptions Handling Exceptionally Sticky Problems.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 15 Exceptions and.
Introduction to Exception Handling and Defensive Programming.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Software Documentation Section 5.5 ALBING’s Section JIA’s Appendix B JIA’s.
Programming with Assertions © Allan C. Milne v
Pre- and postconditions, Using assertions and exceptions 1 Pre- and postconditions Using assertions and exceptions.
David Streader Computer Science Victoria University of Wellington Copyright: David Streader, Victoria University of Wellington Debugging COMP T1.
Exceptions and Assertions Chapter 15 – CSCI 1302.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
SWE 4743 Abstract Data Types Richard Gesick. SWE Abstract Data Types Object-oriented design is based on the theory of abstract data types Domain.
The Java Assertion. 2 Assertion A Java statement in JDK 1.4 & newer Intent: enables code to test assumptions. E.g., a method that calculates the a particle’s.
1 Chapter 15 Exceptions and Assertions. 2 Objectives F To know what is exception and what is exception handling (§15.2). F To distinguish exception types:
Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 15 Exceptions and Assertions Nothing is impossible.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Defensive Programming. Good programming practices that protect you from your own programming mistakes, as well as those of others – Assertions – Parameter.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Winter 2006CISC121 - Prof. McLeod1 Stuff Midterm exam in JEF234 on March 9th from 7- 9pm.
Chapter 13 Exception Handling
Chapter 6 CS 3370 – C++ Functions.
Logger, Assert and Invariants
Testing and Debugging.
Chapter 14: Exception Handling
Programming in Java Assertion.
Exceptions 19-Feb-19.
Exceptions 7-Apr-19.
Exceptions 25-Apr-19.
Exceptions 22-Apr-19.
CSC 143 Java Errors and Exceptions.
Additional control structures
Exceptions 10-May-19.
CS-1020 and Exception Handling
Computer Science 340 Software Design & Testing
Exceptions 5-Jul-19.
Defensive Programming
Presentation transcript:

11-Jun-14 The assert statement

2 About the assert statement The purpose of the assert statement is to give you a way to catch program errors early The assert statement is new in Java 1.4 The assert statement uses a new keyword, assert The new keyword may break older programs that use assert as a user-defined name Hence, there is a way to use the old syntax With the old syntax, assert statements are syntax errors There is also a way to turn off assert statements When they are turned off, Java just ignores assert statements Unfortunately, this also means that your assert statements may be off when you think they are working and doing their job

Turning on assert feature In BlueJ: In Eclipse: make it the default in Window > Preferences > Java > Installed JREs > Edit > Default VM Arguments: -ea Use this line to prove they are on: assert false: "asserts are on"; 3

4 Syntax There are two forms of the assert statement: 1. assert booleanExpression ; This statement tests the boolean expression It does nothing if the boolean expression evaluates to true If the boolean expression evaluates to false, this statement throws an AssertionError 2. assert booleanExpression : expression ; This form acts just like the first form In addition, if the boolean expression evaluates to false, the second expression is used as a detail message for the AssertionError The second expression may be of any type except void

5 Notes on writing assertions An AssertionError is an Error, not an Exception You do not need to put it in a try statement You do not need to catch the error Using an assert statement does not entail any extra work on your part The second expression is seldom necessary If an AssertionError is thrown, Java automatically gives you a stack trace, complete with the line number Use the second expression only if you have useful information to add to the error message

6 Examples – alert for bad data if (x 0;... } switch(suit) { case Suit.CLUBS:... break; case Suit.DIAMONDS:... break; case Suit.HEARTS:... break; case Suit.SPADES:... break; default: assert false: suit; }

7 Assertions vs. Exceptions When do you use assertions instead of exceptions? Both catch problems in your program, but... The intended usage is very different! An exception tells the user of your program that something went wrong An assertion documents something about your program When an assertion fails, it tells you that you have a bug You create Exceptions to deal with problems that you know might occur You write assertions to state things you know (or think you know) about your program

8 When to throw Exceptions Use Exceptions when you: Test whether the parameters to a public method or public constructor are legal If its public, then other people besides you, the author of this class, can call it Do any input/output You, the class author, cannot ensure the files will be there or be correct if they are there In short, Think of yourself as the author of this class only Anything that could go wrong, that you have no control over within this class, deserves an Exception

9 When to use assertions Frequently! Assertions are intended to be cheap to write Just drop them into your code any time you think of them Example: assert age >= 0; How hard is that? Assertions are not intended as a debugging device (though they can be used that way) Rather, assertions should be used to specify things that you believe to be true at various points in your program Assertions provide documentation, not just error checking Assertions are documentation that can be checked by the running program!

10 Invariants An invariant is something that should always be true An internal invariant is a fact that you believe to be true at a certain point in the program assert x > 0; was an example of an internal invariant A control-flow invariant is typically an assertion that you cannot get to certain code assert false: suit; was an example Caution: It is a syntax error to put any code where Java knows you cannot get to it (say, immediately following a return statement) A class invariant is one that an object must satisfy in order to be a valid member of a class Example: assert person.age >= 0 && person.age < 150;

11 When not to use assertions Do not use assertions to do necessary work Assertions can be disabled (turned off) Its a really bad idea to have your program work correctly only when assertions are turned on! Do not use assertions to check the arguments to public methods Argument checking is part of the contract, and should work with or without assertions There are more appropriate Exceptions to throw: IllegalArgumentException, NullPointerException, and IndexOutOfBoundsException are the main ones

12 Assertions can be disallowed Earlier versions of Java did not have assertions Its possible that someone used assert as a variable or method name We still want to be able to use older programs This means we need to be able to disallow assert as a keyword There is no problem with pre-existing binaries (.class files) that used assert as a user-defined name The problem can arise when you recompile old source code By default, javac uses the old syntax (no assert statements), but this will probably change with 1.5 To use assert statements, set a flag in your IDE, or add the flag -source 1.4 to your javac command line Note that the compiler javac has changed, not the interpreter java

13 Assertions can be disabled Disallowing assertions means they are not legal syntax; disabling assertions means they are legal but are turned off By default, assertions are both disallowed and disabled To enable assertions, use the -enableassertions (or - ea ) flag on the java command line You can also enable or disable assertions for a given package or class, but we wont go into that here Assertions are always allowed and enabled in BlueJ and beyond

14 Ensuring assertions are enabled You dont need to explicitly check whether assertions are allowed by the compiler Youll get a syntax error for your assert statement if they are not allowed The following code, placed at the top of a class, will check whether assertions are enabled: static { boolean assertsEnabled = false; assert assertsEnabled = true; // Intentional side effect!!! if (!assertsEnabled) throw new RuntimeException("Asserts must be enabled!!!"); }

15 The End