diff --git a/core-java/src/main/java/com/baeldung/core/exceptions/FileNotFoundExceptionExample.java b/core-java/src/main/java/com/baeldung/core/exceptions/FileNotFoundExceptionExample.java deleted file mode 100644 index 2ac4e49869..0000000000 --- a/core-java/src/main/java/com/baeldung/core/exceptions/FileNotFoundExceptionExample.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.core.exceptions; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; - -public class FileNotFoundExceptionExample { - - public static void main(String[] args) throws IOException { - BufferedReader rd = null; - try { - rd = new BufferedReader(new FileReader(new File("notExisting"))); - rd.readLine(); - } catch (FileNotFoundException ex) { - ex.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionTest.java b/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionTest.java new file mode 100644 index 0000000000..9180edfe81 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionTest.java @@ -0,0 +1,64 @@ +package org.baeldung.core.exceptions; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; + +import org.apache.log4j.Logger; +import org.junit.Test; + +public class FileNotFoundExceptionTest { + + private static final Logger LOG = Logger.getLogger(FileNotFoundExceptionTest.class); + + private String fileName = Double.toString(Math.random()); + + @Test(expected = BusinessException.class) + public void raiseBusinessSpecificException() throws IOException { + try { + readFailingFile(); + } catch (FileNotFoundException ex) { + throw new BusinessException("BusinessException: necessary file was not present.", ex); + } + } + + @Test + public void createFile() throws IOException { + try { + readFailingFile(); + } catch (FileNotFoundException ex) { + try { + new File(fileName).createNewFile(); + readFailingFile(); + System.out.println("File was created and read."); + } catch (IOException ioe) { + throw new RuntimeException("BusinessException: even creation is not possible.", ioe); + } + } + } + + @Test + public void logError() throws IOException { + try { + readFailingFile(); + } catch (FileNotFoundException ex) { + LOG.error("Optional file " + fileName + " was not found.", ex); + System.out.println("File was logged."); + } + } + + protected void readFailingFile() throws IOException { + BufferedReader rd = null; + rd = new BufferedReader(new FileReader(new File(fileName))); + rd.readLine(); + // no need to close file + } + + class BusinessException extends RuntimeException { + public BusinessException(String string, FileNotFoundException ex) { + super(string, ex); + } + } +}