java errors and exceptions · programming and problem solving – java errors and exceptionsspring...

8
Dennis Komm Programming and Problem Solving Java Errors and Exceptions Spring 2019 – March 13, 2019 Java Errors and Exceptions Errors and Exceptions in Java Errors and exceptions interrupt the normal execution of the program abruptly and represent an unplanned event Java allows to catch such events and deal with them as opposed to crashing the entire program Unhandled errors and exceptions are passed up through the call stack Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 1 / 26 Errors Errors happen in the virtual machine of Java and are not fixable Examples No more memory available Too high call stack Missing libraries Bug in the virtual machine Hardware error Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 2 / 26

Upload: others

Post on 24-May-2020

44 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Java Errors and Exceptions · Programming and Problem Solving – Java Errors and ExceptionsSpring 2019Dennis Komm3/26 Exception Types System Exceptions Can happen anywhere Can be

Dennis Komm

Programming and Problem SolvingJava Errors and Exceptions

Spring 2019 – March 13, 2019

Java Errors and Exceptions

Errors and Exceptions in Java

Errors and exceptions interrupt thenormal execution of the program abruptlyand represent an unplanned event

Java allows to catch such events and deal with them

ï as opposed to crashing the entire program

Unhandled errors and exceptions are passed up through the call stack

Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 1 / 26

Errors

Errors happen in the virtual machine of Java andare not fixable

Examples

No more memory available

Too high call stack

Missing libraries

Bug in the virtual machine

Hardware error

Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 2 / 26

Page 2: Java Errors and Exceptions · Programming and Problem Solving – Java Errors and ExceptionsSpring 2019Dennis Komm3/26 Exception Types System Exceptions Can happen anywhere Can be

Exceptions

Exceptions are triggered by the virtual machine or the program itself and cantypically be handled in order to re-establish the normal situation

Examples

De-reference null

Division by zero

Read/write errors (on files)

Errors in business logic

Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 3 / 26

Exception Types

System Exceptions

Can happen anywhere

Can be handled

Cause: bug in the code

Checked Exceptions

Must be declared

Must be handled

Cause: Unlikely but not impossibleevent

Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 4 / 26

Java Errors and ExceptionsSystem Exceptions

Example of a System Exception

import java.util.Scanner;

class ReadTest {public static void main(String[] args) {

int i = readInt("Number");}private static int readInt(String prompt) {

System.out.print(prompt + ": ");Scanner input = new Scanner(System.in);return input.nextInt();

}}

Input

Number: asdfProgramming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 5 / 26

Page 3: Java Errors and Exceptions · Programming and Problem Solving – Java Errors and ExceptionsSpring 2019Dennis Komm3/26 Exception Types System Exceptions Can happen anywhere Can be

Unhandled Errors and Exceptions

The program crashes and leaves behind a stack trace

In there, we can see where the program got interrupted

Exception in thread "main" java.util.InputMismatchException[...]

at java.util.Scanner.nextInt(Scanner.java:2076)at ReadTest.readInt(ReadTest.java:9)at ReadTest.main(ReadTest.java:4)

ï Forensic investigation based on this information

Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 6 / 26

Exception gets Propagated through Call Stack

Java VM Runtime

ReadTest.main

ReadTest.main();

ReadTest.readInt

int i = readInt("Number");

Scanner.nextInt

return input.nextInt();

88

88

88

=

Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 7 / 26

Understanding Stack Traces

Output

Exception in thread "main" java.util.InputMismatchException

at java.util.Scanner.throwFor(Scanner.java:864)

at java.util.Scanner.next(Scanner.java:1485)at java.util.Scanner.nextInt(Scanner.java:2117)at java.util.Scanner.nextInt(Scanner.java:2076)

at ReadTest.readInt(ReadTest.java:9)

at ReadTest.main(ReadTest.java:4) An unsuited input .... . . in method readInt on line 9

. . . called by method main on line 4

Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 8 / 26

Understanding Stack Traces

import java.util.Scanner;class ReadTest {

public static void main(String[] args) {int i = readInt("Number");

}private static int readInt(String prompt) {

System.out.print(prompt + ": ");Scanner input = new Scanner(System.in);return input.nextInt();

}}

at ReadTest.readInt(ReadTest.java:9)at ReadTest.main(ReadTest.java:4)at ReadTest.readInt(ReadTest.java:9)at ReadTest.main(ReadTest.java:4)

Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 9 / 26

Page 4: Java Errors and Exceptions · Programming and Problem Solving – Java Errors and ExceptionsSpring 2019Dennis Komm3/26 Exception Types System Exceptions Can happen anywhere Can be

System Exception – Bug in the Code

Where is the bug?

private static int readInt(String prompt) {System.out.print(prompt + ": ");Scanner input = new Scanner(System.in);return input.nextInt();

}

Not guaranteed that the next input is an int

ï The scanner class provides a test for this

Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 10 / 26

System Exception – Bug Fix

Check first

private static int readInt(String prompt) {System.out.print(prompt + ": ");Scanner input = new Scanner(System.in);if (input.hasNextInt()) {

return input.nextInt();} else {

return 0; // or do something else}

}

Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 11 / 26

First Finding – Often No Exceptional Situation

Often, those “exceptional” cases aren’t that unusual, but pretty foreseeable

In those cases no exceptions should be used

Examples

Wrong credentials when logging in

Empty required fields in forms

Unavailable internet resources

Timeouts

Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 12 / 26

Second Finding – Avoid Exceptions

Instead of letting a runtime exception happen,actively prevent such a situation to arise

Examples

Check user inputs early

Use optional types

Predict timeout situations

Plan B for unavailable resources

Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 13 / 26

Page 5: Java Errors and Exceptions · Programming and Problem Solving – Java Errors and ExceptionsSpring 2019Dennis Komm3/26 Exception Types System Exceptions Can happen anywhere Can be

Exception Types

System Exceptions

Can happen anywhere

Can be handled

Cause: bug in the code

Checked Exceptions

Must be declared

Must be handled

Cause: Unlikely but not impossibleevent

Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 14 / 26

Java Errors and ExceptionsChecked Exceptions

Reading Files in Java

Java has multiple possibilities to read files

We use a combination of FileReader and BufferedReader

This allows to read a file line by line

But what happens if file does not exist?

Java does not allow us to “ignore” this case

ï Checked exception

Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 15 / 26

Example of a Checked Exception

private static String[] readFile(String filename) {FileReader fr = new FileReader(filename);BufferedReader br = new BufferedReader(fr);...line = br.readLine();...

}

Compiler Error./Root/Main.java:9: error: unreported exception FileNotFoundException; must be caught or

declared to be thrownFileReader fr = new FileReader(filename);

^./Root/Main.java:11: error: unreported exception IOException; must be caught or declared

to be thrownString line = br.readLine();

^Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 16 / 26

Page 6: Java Errors and Exceptions · Programming and Problem Solving – Java Errors and ExceptionsSpring 2019Dennis Komm3/26 Exception Types System Exceptions Can happen anywhere Can be

Quick Look into Javadoc

Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 17 / 26

Handling Exceptions

private static String[] readFile(String filename) {try {

FileReader fr = new FileReader(filename);BufferedReader br = new BufferedReader(fr);...line = br.readLine();...

} catch (IOException e) {// do some recovery handling

} finally {// close resources

}}

Protected scope

Measures to re-establish the normalsituation

Gets executed in any case, at theend, always!

Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 18 / 26

Handling Exceptions – Stop Propagation

Java VM Runtime

ReadTest.main

ReadTest.main();

ReadTest.readFile

lines = readFile("dataset.csv");

BufferedReader.readLine

line = br.readLine();

88

4Exception caught!

Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 19 / 26

Finally – Closing Resources

In Java, resources must be closed after use at all costs; otherwise, memory willnot get freed

Files

Data streams

UI elements

. . .

Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 20 / 26

Page 7: Java Errors and Exceptions · Programming and Problem Solving – Java Errors and ExceptionsSpring 2019Dennis Komm3/26 Exception Types System Exceptions Can happen anywhere Can be

Try-With-Resources Statement

Specific syntax to close resources automatically

private static String[] readFile(String filename) {try (FileReader fr = new FileReader(filename);

BufferedReader br = new BufferedReader(fr)) {...line = br.readLine();...

} catch (IOException e) {// do some recovery handling

}}

Resources getopened here

Resources get closed automatically here

Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 21 / 26

Reading in CSV Files

Reading in CSV Files

private static String[] readFile(String filename) {try (FileReader fr = new FileReader(filename);

BufferedReader br = new BufferedReader(fr)) {String line;while (true) {

line = br.readLine();

if (line == null) {break;

}Out.println(line);

}} catch (IOException e) {

// do some recovery handling}

}

String line is assigned next line

Loop is terminated after last line

Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 22 / 26

Reading in CSV Files More “Elegantly”

private static String[] readFile(String filename) {try (FileReader fr = new FileReader(filename);

BufferedReader br = new BufferedReader(fr)) {String line;while ((line = br.readLine()) != null) {

Out.println(line);}

} catch (IOException e) {// do some recovery handling

}}

Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 23 / 26

Page 8: Java Errors and Exceptions · Programming and Problem Solving – Java Errors and ExceptionsSpring 2019Dennis Komm3/26 Exception Types System Exceptions Can happen anywhere Can be

Processing CSV Files

Now every line is read separately and saved to string line

Each line of a CSV file consists of data entries separated by delimiters

Most frequent delimiters are “,” or “;”

Idea: For each line, create string array that consists of this data

Java String offers method split for thisParameter: Delimiter stringReturn value: String array

Example

String[] lineData = line.split(";");

Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 24 / 26

Processing CSV Files

private static String[] readFile(String filename) {try (FileReader fr = new FileReader(filename);

BufferedReader br = new BufferedReader(fr)) {String line;while ((line = br.readLine()) != null) {

String[] lineData = line.split(",");// further process data,// e.g., instantiate data object with lineData// and then save object to appropriate data structure

}} catch (IOException e) {

// do some recovery handling}

}

Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 25 / 26

Processing CSV Files

For objects, other types than floats may be needed

Java has number objects analogous to primitive types

ï For instance Float, Double, Integer (which we have already used as keysfor has maps)

These offer a static function valueOfParameter: StringReturn value: Float

Example

float myFloat = Float.valueOf(lineData[0]);

Programming and Problem Solving – Java Errors and Exceptions Spring 2019 Dennis Komm 26 / 26