forked from angiejones/java-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExceptionHandling.java
More file actions
60 lines (51 loc) · 1.66 KB
/
Copy pathExceptionHandling.java
File metadata and controls
60 lines (51 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package chapter13;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ExceptionHandling {
public static void main(String args[]){
createNewFile();
numbersExceptionHandling();
}
public static void createNewFile(){
File file = new File("resources/nonexistent.txt");
try{
file.createNewFile();
}catch (Exception e){
System.out.println("Directory does not exist.");
e.printStackTrace();
}
}
public static void createNewFileRethrow() throws IOException{
File file = new File("resources/nonexistent.txt");
file.createNewFile();
}
public static void numbersExceptionHandling(){
File file = new File("resources/numbers.txt");
Scanner fileReader = null;
try{
fileReader = new Scanner(file);
while(fileReader.hasNext()){
double num = fileReader.nextDouble();
System.out.println(num);
}
}catch(FileNotFoundException | InputMismatchException e){
e.printStackTrace();
}finally{
fileReader.close();
}
}
public static void tryWithResources(){
File file = new File("resources/numbers.txt");
try(Scanner fileReader = new Scanner(file)){
while(fileReader.hasNext()){
double num = fileReader.nextDouble();
System.out.println(num);
}
}catch(FileNotFoundException | InputMismatchException e){
e.printStackTrace();
}
}
}