Beruflich Dokumente
Kultur Dokumente
Flow Control
Exceptions
Alice Laic
endava.com
if statement
Conditional operator
Decision Statements switch statement
2
if statement
3
if statement - exercise
int x = 3; 4
if (x = 5) {}
• What about this one?
4
Conditional operator
5
result = (age < 18) ? “minor” : “adult”;
is equivalent to:
5
switch statement
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
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
10
for-each statement
11
while statement
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
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
• 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;
}
21
Catching And Handling - finally
try {
//code
} catch … {
//TODO when this exception occurs
} finally {
//TODO cleanup code
} 22
22
Catching And Handling - finally
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
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
27
27
Unchecked Exceptions
• 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)
30
Exceptions – exercises (2)
31
Exceptions – exercises (3)
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
34
Questions?
35
35
Thank you!
Alice Laic
Software36Developer
alice.laic@endava.com
en_alaic
36