Sei sulla pagina 1di 36

QUALITY. PRODUCTIVITY. INNOVATION.

Flow Control
Exceptions
Alice Laic

endava.com
 if statement
 Conditional operator
Decision Statements  switch statement

2
if statement

• controls the flow of execution based on a logical expression

if (hourOfDay > 18) {


System.out.println(“Go home!");
} else { 3
work();
}

if ((speed = speed + 10) < legalSpeedLimit) {


System.out.println("Need 4 Speed!");
}

3
if statement - exercise

boolean boo = false;


if( boo = true) {}

• What’s your opinion?

int x = 3; 4
if (x = 5) {}
• What about this one?

4
Conditional operator

• a condensed, limited form of an if statement


• limited because multiple statements cannot be included in the then or else
clauses

LogicalExpression ? ThenExpression : ElseExpression

5
result = (age < 18) ? “minor” : “adult”;

is equivalent to:

if (age < 18)


result = “minor”;
else
result = “adult”;

5
switch statement

• fixed number of execution paths


• works with the primitives: byte, short, int and char
• also works with: Byte, Short, Integer, Character, Enum and String
(starting from Java 7)
• use break to exit the statement
• use when in need to check fixed values
6

switch (age) {
case 14: System.out.println(“You need an ID");
break;
case 18: System.out.println(“Time to change the ID");
break;
default: System.out.println(“That’s fine");
}

6
switch statement

switch (day) {
case "MON":
case "TUE":
case "WED":
case "THU": System.out.println("Time to work");
break; 7
case "FRI": System.out.println("Nearing weekend");
case "SAT":
case "SUN": System.out.println(“Party!");
break;
default: System.out.println("Invalid day");
}

7
switch statement

switch(x) {
case 2: System.out.println(“2”);
default: System.out.println(“default”);
case 3: System.out.println(“3”);
case 4: System.out.println(“4”);
} 8

What the result will be for x=7? But for x = 2?

8
 for statement
 for-each statement
Looping Constructs  while statement
 do-while statement
 Branching statements
• break
• continue
• return
• Nested loops, labels
 Pitfalls

9
for statement

• usually used to execute a set of statements a fixed number of times

int sum = 0; int[] array = ...;


for (int i = 0; i < array.length; i++) {
sum = sum + array[i]; 10
}

for (int i = 0, j = 10; j > 5 && i < 3; i++, j--) {


System.out.println (i + " " + j);
}

10
for-each statement

• simpler and more readable


• easier way to iterate through each member of an array or class that has
implemented the java.util.Iterable interface
Drawbacks:
• impossible to modify the current position in an array or list
• impossible to directly iterate over multiple arrays or collections
11

int sum = 0; int[] array = ...;


for (int value : array) {
sum = sum + value;
}

11
while statement

• used when the number of times a block is to be executed is not known


• expression is evaluated at the beginning of the loop

while (!notAwake) {
drinkCoffee(); 12
}

int i = 1;
while (i++ < 10) {
System.out.println(i);
}

12
do-while statement

• also used when the number of times a block is to be executed is not known
• expression is evaluated at the end of the loop
• the body of the loop always executes at least once

int i = 2; 13
do {
System.out.println(i);
} while (++i <= 10);

13
Branching statements

• the break statement terminates the current loop and passes control to the
statement following the loop
• the continue statement is used to skip to the end of the inner-most loop’s body
and evaluate the expression without exiting the loop
• labels can be used to alter the flow of control
• the return statement is used to exit from current method
14
search:
for (int i = 0; i < arrayOfInts.length; i++)
for (int j = 0; j < arrayOfInts[i].length; j++)
if (arrayOfInts[i][j] == searchFor) {
foundIt = true;
break search;
}

14
Pitfalls

while (waterLevel < 10);


raiseWaterLevel();

15
for (int i = 0; i < 5; i++)
product = i * i;
sum += product;

15
Pitfalls

float x = 0.1f;
while (x != 1.1f) {
x = x + 0.1f;
} 16

if (someNumber >= 0)
if (someNumber == 0)
System.out.println(“first”);
else System.out.println(“second”);
System.out.println(“third”);

16
 Catching and Handling
 Throw Exceptions
Exceptions  Throwable Hierarchy
 Custom Exception
 Unchecked Exceptions
 Summary
 Exercises
 Questions?

17
Catching And Handling - try

try {
code
}
catch or/and finally blocks . . .

• 18
Code: piece of code that might throw an exception

• If an exception occurs within the try block, that exception is handled by an exception
handler associated with it -> catch block

18
Catching And Handling - catch

try {
//code try {
} catch (ExceptionType1 name) { //code
//TODO when this exception occurs } catch (ExType1|ExType2 ex){
} catch (ExceptionType2 name) { //TODO when this exception occurs

//TODO when this exception occurs


}
} 19

• Catch block- exception handler -> handles the exception specified by the argument

• ExceptionType<number> -> declares the type of exception that the handler can handle
and must be the name of a class that inherits from the Throwable class

19
Catching And Handling - catch

try {
System.out.println(computeResultD(inputValues));
System.out.println(computeResultI(inputValues));
} catch (NumberFormatException ex) {
System.out.println("Invalid number format!");
} catch (ArithmeticException ex) {
System.out.println("Invalid arguments!");
}

20

private static double computeResultD (String... inputValues) private static Integer computeResultI (String... inputValues)
{ {
double a = Double.parseDouble(inputValues[0]); Integer a = Integer.parseInt(inputValues[0]);
double b = Double.parseDouble(inputValues[1]); Integer b = Integer.parseInt(inputValues[1]);
return a / b; return a / b;
} }

20
Catching And Handling - catch
NumberFormatException e1 = null
try {
System.out.println(computeResultD(inputValues));
System.out.println(computeResultI(inputValues));
} catch (NumberFormatException|ArithmeticException ex) {
ex = e1;
}

• Is this code ok? 21

21
Catching And Handling - finally

try {
//code
} catch … {
//TODO when this exception occurs
} finally {
//TODO cleanup code
} 22

• Finally blocks -> always executes when a try exists.


-> key tool to prevent resource leaks (files that aren’t closed, etc..)

22
Catching And Handling - finally

public int readFirstByte(String name) {


InputStream is = null;
try {
is = new FileInputStream(name); //FileNotFoundException
return is.read(); //IOException
} catch (FileNotFoundException ex) {
ex.printStackTrace(); 23
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (is != null)
try { is.close(); } //IOException
catch (IOException ex) { ex.printStackTrace(); }
}
}

23
Catching And Handling –
try-with-resources
static String readFirstLineFromFile(String path) throws IOException
{
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}
} 24

24
Throw exceptions

public Object pop() {


Object obj;

if (size == 0) {
throw new EmptyStackException();
}
25
obj = objectAt(size - 1);
setObjectAt(size - 1, null);
size--;
return obj;
}

25
Throwable Hierarchy

26

26
Custom Exception

public class CustomException extends Exception{

27

27
Unchecked Exceptions

• RuntimeException, Error, and their subclasses

• Runtime exceptions: exceptional conditions that are internal to the application, and that
the application usually cannot anticipate or recover from (usually programming bugs)
28

• Error: exceptional conditions that are external to the application, and that the
application usually cannot anticipate or recover from

28
Exceptions - summary

• a program can catch exceptions by using a combination of the try, catch, and finally
blocks.
• be specific about the exception you need to catch (avoid catching java.lang.Exception)
• the finally block identifies a block of code that is guaranteed to execute, and is the right
place to close files, recover resources, and otherwise clean up after the code enclosed
in the try block. 29
• the try statement should contain at least one catch block or a finally block and may
have multiple catch blocks.
• don’t ignore exceptions! they are thrown for a reason and if there is something you can do
to recover, then you should deal with it
• do not use exceptions to control normal logic flow (perform validation!)
• do not try to handle unchecked exceptions

29
Exceptions – exercises (1)

public static int check(){


try{
throw new FileNotFoundException();
//return 4;
}catch(FileNotFoundException ex){
return 2; 30
}finally{
return 3;
}
}

30
Exceptions – exercises (2)

public static int check(){


try{
throw new FileNotFoundException();
}catch(FileNotFoundException ex){
throw new IOException();
}finally{ 31
return 3;
}
}

• What happens when commenting the first throw clause?


• What happens when commenting return 3?

31
Exceptions – exercises (3)

class SubException extends Exception{}


class SubSubException extends SubException{}

public class CC {
void doStuff() throws SubException{};
32
}
class CC2 extends CC {
@Override
void doStuff() throws SubSubException {}
}

32
Exceptions – exercises (3)
class CC3 extends CC {
@Override
void doStuff() throws Exception {}
}

33
class CC4 extends CC {
void doStuff(int x) throws Exception {}
}
class CC5 extends CC {
@Override
void doStuff() {}
}

33
Exceptions - exercises

Please read the following resources and try to do the exercises:


34
- https://docs.oracle.com/javase/tutorial/essential/exceptions/
- Exceptions Chapter from SCJP 7

34
Questions?
35

35
Thank you!

Alice Laic
Software36Developer

alice.laic@endava.com
en_alaic

36

Potrebbero piacerti anche