I am creating program which will parse .csv file and I am using FileReader and Scanner classes from java API.
FileReader throws FileNotFoundException, IOException.
Scanner's method hasNextLine() and nextLine() throw IllegalStateException and NoSuchElementException.
Should I use 1 try and 4 multiple catch blocks? Or try block nested in another try block(which has 2 catch blocks) with 2 catch blocks?
Code 1:
import java.io.*;
import java.util.Scanner;
import java.util.NoSuchElementException;
import java.lang.IllegalStateException;
public class App {
public static void main(String[] args) {
try (FileReader file = new FileReader("Doc.csv")) {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
} catch (IllegalStateException e) {
System.out.println(e);
} catch (NoSuchElementException e) {
System.out.println(e);
} catch (FileNotFoundException e) {
System.out.println(e);
} catch (IOException e) {
System.out.println(e);
}
}
}
Code 2:
import java.io.*;
import java.util.Scanner;
import java.util.NoSuchElementException;
import java.lang.IllegalStateException;
public class App {
public static void main(String[] args) {
try (FileReader file = new FileReader("Doc.csv")) {
Scanner sc = new Scanner(file);
try {
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
} catch (IllegalStateException e) {
System.out.println(e);
} catch (NoSuchElementException e) {
System.out.println(e);
}
} catch (FileNotFoundException e) {
System.out.println(e);
} catch (IOException e) {
System.out.println(e);
}
}
}
By the way, I know that System.out.println(e) is not best practice for logging exception. So, please don't write about it