ExceptionHandlerQueueThenThrowAfter.java

  1. package com.opencsv.bean.exceptionhandler;

  2. import com.opencsv.exceptions.CsvException;

  3. import java.util.concurrent.atomic.AtomicInteger;

  4. /**
  5.  * <p>An exception handler that queues the first x exceptions, then throws any
  6.  * further exceptions.</p>
  7.  *
  8.  * <p><b>Note:</b> when testing this on systems with a high number of cores/threads under
  9.  * load we noted discrepancies between the number of exceptions counted and the number
  10.  * exceptions queued.   If it is actually important to see the exceptions thrown then
  11.  * we would heavily recommend you use the single threaded iterator() in CsvToBean
  12.  * and collecting the exceptions yourself.</p>
  13.  *
  14.  * @author Andrew Rucker Jones
  15.  * @since 5.2
  16.  */
  17. final public class ExceptionHandlerQueueThenThrowAfter implements CsvExceptionHandler {

  18.     private final AtomicInteger count = new AtomicInteger();
  19.     private final int maxExceptions;

  20.     /**
  21.      * Creates an instance.
  22.      * @param maxExceptions The number of exceptions that will be queued. Any
  23.      *                      exception handled after this limit will be thrown.
  24.      */
  25.     public ExceptionHandlerQueueThenThrowAfter(int maxExceptions) {
  26.         this.maxExceptions = maxExceptions;
  27.     }

  28.     @Override
  29.     public CsvException handleException(CsvException e) throws CsvException {
  30.         if(count.incrementAndGet() > maxExceptions) {
  31.             throw e;
  32.         }
  33.         return e;
  34.     }
  35. }