Sei sulla pagina 1di 41

Flow Control, Exceptions and

Assertions

Objectives
• Write code using if and switch statements, and identify legal argument types for these
statements.
• Write code using all forms of loops, including labeled and unlabeled use
of break and continue, and state the values taken by loop counter variables during and after
loop execution.
• Write code that makes proper use of exceptions and exception handling clauses (try-catch-
finally), and declares methods and overriding methods that throw exceptions.
• Recognize the effect of an exception arising at a specified point in a code fragment. Note:
The exception may be a runtime exception, a checked exception, or an error (the code may
include try, catch, or finally clauses in any legitimate combination).
• Write code that makes proper use of assertions, and distinguish appropriate from
inappropriate uses of assertions.
• Identify correct statements about the assertion mechanism.
Control Flow Statements

The statements inside your source files are generally


executed from top to bottom in the order that they appear.
Control flow statements, however, break up the flow of
execution by employing decision making, looping and
branching, enabling your program to conditionally execute
particular blocks of code. The various control-flow
statements are: the decision-making/Selection statements (if-
then, if-then-else, switch), The looping/Iteration statements (for,
while, do-while), and the branching/transfer statements (break,
continue, return).
The simple if and if-else Statements

 The simple if/if-then Statement


The simple if statement is the, most basic of all the
control flow statements. It tells your program to execute a certain
section of code only if a particular test evaluates to true.
Basic Format of an if statement
if (booleanExpression) {
System.out.println("Inside if statement");
}
 The if-else/if-then-else Statement
The if-then-else statement provides a secondary path of
execution when an *if* clause evaluates to false.
Rules for using else and else if

 You can have zero or one else for a given if, and it must
come after any else ifs.
 You can have zero to many else ifs for a given if and they
must come before the (optional) else.
 Once an else if succeeds, none of the remaining else ifs or
elses will be tested
Sample

public class Test 1{


public static void main(String[] args) {
boolean boo = false;
if(boo = true){
}
}
}

public class Test 2{


public static void main(String[] args) {
int x = 3;
if(x=5){
}
}
}
switch Statements

 Legal Expressions for switch and case


switch (expression) {
case constant1: code block
case constant2: code block
default: code block
}
Sample

final int a = 1;
final int b:
b =2;
int x = 0;
switch (x) {
case a:
case b:
Sample

byte g = 2;
switch(g) {
case 23:
case 128:
}
---------------------------------------------------------------------------------------------------------
int temp = 90;
switch(temp) {
case 80 : System.out.println("80");
case 80 : System.out.println("80"); // won't compile!
case 90 : System.out.println("90");
default : System.out.println("default");
}
Loops and Iterators

 All loops are controlled by a boolean expression.


 Loops allow a block of statements to be executed
repeatedly (i.e., iterated).
 A boolean condition (called the loop condition) is
commonly used to determine when to terminate the loop.
 The statements executed in the loop constitute the loop
body. The loop body can be a single statement or a block.
Java provides three language constructs
for constructing loops:

while statement

do-while statement

for statement
while Loops

The while statement continually executes a block of statements while a particular condition is
true.
The while loop is good for scenarios where you don't know how many times a block or statement
should repeat, but you want to continue looping as long as some condition is true.
Its syntax can be expressed as:

while (expression)
{
statement(s)
}
The while statement evaluates expression, which must return a boolean value. If the
expression evaluates to true, the while statement executes the statement(s) in the while
block. The while statement continues testing the expression and executing its block until the
expression evaluates to false
do Loops or do-while Loops

The do loop is similar to the while loop, except that the


expression is not evaluated until after the do loop's code is
executed. Therefore the code in a do loop is guaranteed to
execute at least once. The following shows a do loop in
action:
Syntax:
do {
statement(s)
} while (expression);
for Loops

The for statement provides a compact way to iterate over a


range of values. Programmers often refer to it as the "for
loop" because of the way in which it repeatedly loops until a
particular condition is satisfied.
Basic for loop

 The for loop is especially useful for flow control when you
already know how many times you need to execute the
statements in the loop's block. The for loop declaration has
three main parts, besides the body of the loop:

The general form of the for statement can be expressed as


follows:
for (/*Initialization*/ ; /*Condition*/ ; /* Iteration */) {
/* loop body */
}
exit in for loop

Code in Loop : What Happens


break = Execution jumps immediately to the 1st statement
after the for loop.
return = Execution jumps immediately back to the calling
method.
System.exit() = All program execution stops; the VM shuts
down.
Enhanced for Loop

Format of enhanced for loop:

for(declaration : expression)

The two pieces of the for statement are


 declaration The newly declared block variable, of a type compatible
with the elements of the array you are accessing. This variable will be
available within the for block, and its value will be the same as the
current array element.
 expression This must evaluate to the array you want to loop through.
This could be an array variable or a method call that returns an array.
The array can be any type: primitives, objects, even arrays of arrays.
Branching statements

 Using break and continue


The break and continue keywords are used to stop either the
entire loop (break) or just the current iteration (continue).
Typically if you're using break or continue, you'll do an if
test within the loop, and if some condition becomes true (or
false depending on the program), you want to get out
immediately. The difference between them is whether or not
you continue with a new iteration or jump to the first
statement below the loop and continue from there.
Branching statements

 Both the break statement and the continue statement can


be
 unlabeled
 Labeled

 reutnm
Handling Exceptions

Still, error detection and handling may be the most important


ingredient of any robust application. Java arms developers with an
elegant mechanism for handling errors that produces efficient and
organized error-handling code: exception handling.
Exception handling allows developers to detect errors easily
without writing special code to test return values. Even better, it
lets us keep exception-handling code cleanly separated from the
exception-generating code. It also lets us use the same exception-
handling code to deal with a range of possible exceptions.
Catching an Exception
Using try and catch

 1. try {
 2. // This is the first line of the "guarded region"
 3. // that is governed by the try keyword.
 4. // Put code here that might cause some kind of exception.
 5. // We may have many code lines here or just one.
 6. }
 7. catch(MyFirstException) {
 8. // Put code here that handles this exception.
 9. // This is the next line of the exception handler.
 10. // This is the last line of the exception handler.
 11. }
 12. catch(MySecondException) {
 13. // Put code here that handles this exception
 14. }
 15.
 16. // Some other unguarded (normal, non-risky) code begins here
finally

1: try {
2: // This is the first line of the "guarded region".
3: }
4: catch(MyFirstException) {
5: // Put code here that handles this exception
6: }
7: catch(MySecondException) {
8: // Put code here that handles this exception
9: }
10: finally {
11: // Put code here to release any resource we
12: // allocated in the try clause.
13: }
14:
15: // More code here
finally

try {
// do stuff
} finally {
//clean up
}
Exception Handling

• If an exception is ignored by the program, the program


will terminate abnormally and produce an appropriate
message

• The message includes a call stack trace that:


 indicates the line on which the exception occurred

 shows the method call trail that lead to the attempted


execution of the offending line
Exception Propagation

 An exception can be handled at a higher level if it is


not appropriate to handle it where it occurs
 Exceptions propagate up through the method calling
hierarchy until they are caught and handled or until
they reach the level of the main method
 A try block that contains a call to a method in which
an exception is thrown can be used to catch that
exception
When an uncaught exception occurs, the
JVM does the following:

 It calls a special private method,


dispatchUncaughtException(), on the Thread class in
which the exception occurs;
 It then terminates the thread in which the exception
occurred1.
Exception Hierarchy

• Classes that define exceptions are related by inheritance,


forming an exception class hierarchy

• All error and exception classes are descendents of the


Throwable class

• A programmer can define an exception by extending the


Exception class or one of its descendants

• The parent class used depends on how the new exception will
be used
Exception Hierarchy
Handling an Entire
Class Hierarchy of Exceptions

try {
// Some code here that can throw a boundary exception
}
catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
Handling an Entire
Class Hierarchy of Exceptions

try {
// some code
}
catch (Exception e) {
e.printStackTrace();
}
Exception Declaration and the
Public Interface

void myFunction() throws MyException1, MyException2 {


// code for the method here
}
Checked Exceptions

• An exception is either checked or unchecked


• A checked exception either must be caught by a method, or
must be listed in the throws clause of any method that may
throw or propagate it
• A throws clause is appended to the method header
• The compiler will issue an error if a checked exception is
not caught or asserted in a throws clause
Unchecked Exceptions

• An unchecked exception does not require explicit handling,


though it could be processed that way

• The only unchecked exceptions in Java are objects of type


RuntimeException or any of its descendants

• Errors are similar to RuntimeException and its


descendants in that:
 Errors should not be caught
 Errors do not require a throws clause
The throw Statement

• Exceptions are thrown using the throw statement

• Usually a throw statement is executed inside an if


statement that evaluates a condition to see if the
exception should be thrown
Sample of Bad Exception catching

try {
callBadMethod();
} catch (Exception ex) { }
Rethrowing the Same Exception

catch(IOException e) {
// Do things, then if you decide you can't handle it…
throw e;
}
----------------------------------------------------------------------------
public void doStuff() {
try {
// risky IO things
} catch(IOException ex) {
// can't handle it
throw ex; // Can't throw it unless you declare it
}
}
Where Exceptions Come From

 JVM exceptions Those exceptions or errors that are


either exclusively or most logically thrown by the JVM.
Ex: NullPointerException.
 Programmatic exceptions Those exceptions that are
thrown explicitly by application and/or API programmers
Common Exceptions
Assertions

 The following two forms of the assert statement can be


used to specify assertions:

assert <boolean expression> ; // the really simple form


assert <boolean expression> : <message expression> ;
// the simple form or the augmented form
Assertion Expression Rules

 Assertions can have either one or two expressions,


depending on whether you're using the "simple" or the
"really simple." The first expression must always result in a
boolean value! Follow the same rules you use for if and
while tests. The whole point is to assert aTest, which
means you're asserting that aTest is true. If it is true, no
problem. If it's not true, however, then your assumption
was wrong and you get an AssertionError.
Where not to use Assertion

 According to Sun Specification, assertion should not be


used to check arguments in the public methods because it
should result in appropriate runtime exception e.g.
IllegalArgumentException, NullPointerException etc.
 Do not use assertion, if you don't want any error in any
situation.
End

Potrebbero piacerti anche