How to include current date when logging exceptions to a file with FileOutputStream in java?

Java 8Object Oriented ProgrammingProgramming

There are several logging frame works available to log your data into files. You can also define your own method. In either cases to add the current time to your logged exception you can use the LocalDateTime class.

It is an immutable class representing the date-time, it stores date-time as year-month-day-hour-minute-second. The now() method of this class returns the current date-time.

Using this method concatenate the current date and time to your exception message and write to your required file.


import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Scanner;
public class LoggingToFile {
   private static void writeLogToFile(Exception e) throws IOException {
      FileOutputStream writer = new FileOutputStream("ExceptionLog.txt");
      byte bytes[] = (": "+e.toString()).getBytes();
      System.out.println("Exception logged to your file");
   public static void main(String [] args) throws IOException {
      Scanner sc = new Scanner(;
      int[] arr = {10, 20, 30, 2, 0, 8};
      System.out.println("Array: "+Arrays.toString(arr));
      System.out.println("Choose numerator and denominator (not 0) from this array (enter positions 0 to 5)");
      int a = sc.nextInt();
      int b = sc.nextInt();
      try {
         int result = (arr[a])/(arr[b]);
         System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
      }catch(ArrayIndexOutOfBoundsException ex) {
         System.out.println("Warning: You have chosen a position which is not in the array");
      }catch(ArithmeticException ex) {
         System.out.println("Warning: You cannot divide a number with 0");


Enter 3 integer values one by one:
Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator (not 0) from this array (enter positions 0 to 5)
Warning: You cannot divide a number with 0
Exception logged to your file
Published on 06-Aug-2019 07:50:57