From f56bf16d112c600fc1c6422341fcf4d91c1a52e0 Mon Sep 17 00:00:00 2001 From: Mrudav Shukla Date: Sun, 8 Jul 2018 17:41:29 +0530 Subject: [PATCH] BAEL-1921 - added example code and unit test for GlobalExceptionHandler (#4646) * added example code and unit test for GlobalExceptionHandler * Code for common exceptions --- .../reflection/exceptions/Arithmetic.java | 20 ++++++ .../exceptions/ArrayIndexOutOfBounds.java | 24 +++++++ .../reflection/exceptions/ClassCast.java | 36 +++++++++++ .../reflection/exceptions/FileNotFound.java | 25 ++++++++ .../exceptions/GlobalExceptionHandler.java | 28 ++++++++ .../exceptions/IllegalArgument.java | 18 ++++++ .../reflection/exceptions/IllegalState.java | 32 ++++++++++ .../InterruptedExceptionExample.java | 28 ++++++++ .../reflection/exceptions/MalformedURL.java | 25 ++++++++ .../reflection/exceptions/NullPointer.java | 36 +++++++++++ .../reflection/exceptions/NumberFormat.java | 23 +++++++ .../exceptions/ParseExceptionExample.java | 25 ++++++++ .../exceptions/StringIndexOutOfBounds.java | 23 +++++++ .../GlobalExceptionHandlerUnitTest.java | 64 +++++++++++++++++++ 14 files changed, 407 insertions(+) create mode 100644 core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/Arithmetic.java create mode 100644 core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/ArrayIndexOutOfBounds.java create mode 100644 core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/ClassCast.java create mode 100644 core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/FileNotFound.java create mode 100644 core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/GlobalExceptionHandler.java create mode 100644 core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/IllegalArgument.java create mode 100644 core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/IllegalState.java create mode 100644 core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/InterruptedExceptionExample.java create mode 100644 core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/MalformedURL.java create mode 100644 core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/NullPointer.java create mode 100644 core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/NumberFormat.java create mode 100644 core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/ParseExceptionExample.java create mode 100644 core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/StringIndexOutOfBounds.java create mode 100644 core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/exceptions/GlobalExceptionHandlerUnitTest.java diff --git a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/Arithmetic.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/Arithmetic.java new file mode 100644 index 0000000000..138916ec60 --- /dev/null +++ b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/Arithmetic.java @@ -0,0 +1,20 @@ +package com.baeldung.exceptions; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class Arithmetic { + + private static Logger LOGGER = LoggerFactory.getLogger(Arithmetic.class); + + public static void main(String[] args) { + + try { + int result = 30 / 0; // Trying to divide by zero + } catch (ArithmeticException e) { + LOGGER.error("ArithmeticException caught!"); + } + + } + +} diff --git a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/ArrayIndexOutOfBounds.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/ArrayIndexOutOfBounds.java new file mode 100644 index 0000000000..93b53f284c --- /dev/null +++ b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/ArrayIndexOutOfBounds.java @@ -0,0 +1,24 @@ +package com.baeldung.exceptions; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ArrayIndexOutOfBounds { + + private static Logger LOGGER = LoggerFactory.getLogger(ArrayIndexOutOfBounds.class); + + public static void main(String[] args) { + + int[] nums = new int[] { 1, 2, 3 }; + + try { + int numFromNegativeIndex = nums[-1]; // Trying to access at negative index + int numFromGreaterIndex = nums[4]; // Trying to access at greater index + int numFromLengthIndex = nums[3]; // Trying to access at index equal to size of the array + } catch (ArrayIndexOutOfBoundsException e) { + LOGGER.error("ArrayIndexOutOfBoundsException caught"); + } + + } + +} diff --git a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/ClassCast.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/ClassCast.java new file mode 100644 index 0000000000..183f8f54a3 --- /dev/null +++ b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/ClassCast.java @@ -0,0 +1,36 @@ +package com.baeldung.exceptions; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +class Animal { + +} + +class Dog extends Animal { + +} + +class Lion extends Animal { + +} + +public class ClassCast { + + private static Logger LOGGER = LoggerFactory.getLogger(ClassCast.class); + + public static void main(String[] args) { + + try { + Animal animalOne = new Dog(); // At runtime the instance is dog + Dog bruno = (Dog) animalOne; // Downcasting + + Animal animalTwo = new Lion(); // At runtime the instance is animal + Dog tommy = (Dog) animalTwo; // Downcasting + } catch (ClassCastException e) { + LOGGER.error("ClassCastException caught!"); + } + + } + +} diff --git a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/FileNotFound.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/FileNotFound.java new file mode 100644 index 0000000000..bb9e0bf4ac --- /dev/null +++ b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/FileNotFound.java @@ -0,0 +1,25 @@ +package com.baeldung.exceptions; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class FileNotFound { + + private static Logger LOGGER = LoggerFactory.getLogger(FileNotFound.class); + + public static void main(String[] args) { + + BufferedReader reader = null; + try { + reader = new BufferedReader(new FileReader(new File("/invalid/file/location"))); + } catch (FileNotFoundException e) { + LOGGER.error("FileNotFoundException caught!"); + } + } + +} diff --git a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/GlobalExceptionHandler.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/GlobalExceptionHandler.java new file mode 100644 index 0000000000..ab46c83da4 --- /dev/null +++ b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/GlobalExceptionHandler.java @@ -0,0 +1,28 @@ +package com.baeldung.exceptions; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class GlobalExceptionHandler { + + public static void main(String[] args) { + + Handler globalExceptionHandler = new Handler(); + Thread.setDefaultUncaughtExceptionHandler(globalExceptionHandler); + new GlobalExceptionHandler().performArithmeticOperation(10, 0); + } + + public int performArithmeticOperation(int num1, int num2) { + return num1/num2; + } + +} + +class Handler implements Thread.UncaughtExceptionHandler { + + private static Logger LOGGER = LoggerFactory.getLogger(Handler.class); + + public void uncaughtException(Thread t, Throwable e) { + LOGGER.info("Unhandled exception caught!"); + } +} diff --git a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/IllegalArgument.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/IllegalArgument.java new file mode 100644 index 0000000000..801536cb2d --- /dev/null +++ b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/IllegalArgument.java @@ -0,0 +1,18 @@ +package com.baeldung.exceptions; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class IllegalArgument { + + private static Logger LOGGER = LoggerFactory.getLogger(IllegalArgument.class); + + public static void main(String[] args) { + try { + Thread.sleep(-1000); + } catch (InterruptedException e) { + LOGGER.error("IllegalArgumentException caught!"); + } + } + +} diff --git a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/IllegalState.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/IllegalState.java new file mode 100644 index 0000000000..e8ddcea3c2 --- /dev/null +++ b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/IllegalState.java @@ -0,0 +1,32 @@ +package com.baeldung.exceptions; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class IllegalState { + + private static Logger LOGGER = LoggerFactory.getLogger(IllegalState.class); + + public static void main(String[] args) { + + List intList = new ArrayList<>(); + + for (int i = 0; i < 10; i++) { + intList.add(i); + } + + Iterator intListIterator = intList.iterator(); // Initialized with index at -1 + + try { + intListIterator.remove(); // IllegalStateException + } catch (IllegalStateException e) { + LOGGER.error("IllegalStateException caught!"); + } + + } + +} diff --git a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/InterruptedExceptionExample.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/InterruptedExceptionExample.java new file mode 100644 index 0000000000..319fd33591 --- /dev/null +++ b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/InterruptedExceptionExample.java @@ -0,0 +1,28 @@ +package com.baeldung.exceptions; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +class ChildThread extends Thread { + + private static Logger LOGGER = LoggerFactory.getLogger(ChildThread.class); + + public void run() { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + LOGGER.error("InterruptedException caught!"); + } + } + +} + +public class InterruptedExceptionExample { + + public static void main(String[] args) throws InterruptedException { + ChildThread childThread = new ChildThread(); + childThread.start(); + childThread.interrupt(); + } + +} diff --git a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/MalformedURL.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/MalformedURL.java new file mode 100644 index 0000000000..57fcddf76b --- /dev/null +++ b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/MalformedURL.java @@ -0,0 +1,25 @@ +package com.baeldung.exceptions; + +import java.net.MalformedURLException; +import java.net.URL; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MalformedURL { + + private static Logger LOGGER = LoggerFactory.getLogger(MalformedURL.class); + + public static void main(String[] args) { + + URL baeldungURL = null; + + try { + baeldungURL = new URL("malformedurl"); + } catch (MalformedURLException e) { + LOGGER.error("MalformedURLException caught!"); + } + + } + +} diff --git a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/NullPointer.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/NullPointer.java new file mode 100644 index 0000000000..2402a786a9 --- /dev/null +++ b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/NullPointer.java @@ -0,0 +1,36 @@ +package com.baeldung.exceptions; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class NullPointer { + + private static Logger LOGGER = LoggerFactory.getLogger(NullPointer.class); + + public static void main(String[] args) { + + Person personObj = null; + + try { + String name = personObj.personName; // Accessing the field of a null object + personObj.personName = "Jon Doe"; // Modifying the field of a null object + } catch (NullPointerException e) { + LOGGER.error("NullPointerException caught!"); + } + + } +} + +class Person { + + public String personName; + + public String getPersonName() { + return personName; + } + + public void setPersonName(String personName) { + this.personName = personName; + } + +} diff --git a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/NumberFormat.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/NumberFormat.java new file mode 100644 index 0000000000..7050e70aee --- /dev/null +++ b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/NumberFormat.java @@ -0,0 +1,23 @@ +package com.baeldung.exceptions; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class NumberFormat { + + private static Logger LOGGER = LoggerFactory.getLogger(NumberFormat.class); + + public static void main(String[] args) { + + String str1 = "100ABCD"; + + try { + int x = Integer.parseInt(str1); // Converting string with inappropriate format + int y = Integer.valueOf(str1); + } catch (NumberFormatException e) { + LOGGER.error("NumberFormatException caught!"); + } + + } + +} diff --git a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/ParseExceptionExample.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/ParseExceptionExample.java new file mode 100644 index 0000000000..f7fb4c91e4 --- /dev/null +++ b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/ParseExceptionExample.java @@ -0,0 +1,25 @@ +package com.baeldung.exceptions; + +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ParseExceptionExample { + + private static Logger LOGGER = LoggerFactory.getLogger(ParseExceptionExample.class); + + public static void main(String[] args) { + + DateFormat format = new SimpleDateFormat("MM, dd, yyyy"); + + try { + format.parse("01, , 2010"); + } catch (ParseException e) { + LOGGER.error("ParseException caught!"); + } + } + +} diff --git a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/StringIndexOutOfBounds.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/StringIndexOutOfBounds.java new file mode 100644 index 0000000000..bc297be498 --- /dev/null +++ b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exceptions/StringIndexOutOfBounds.java @@ -0,0 +1,23 @@ +package com.baeldung.exceptions; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class StringIndexOutOfBounds { + + private static Logger LOGGER = LoggerFactory.getLogger(StringIndexOutOfBounds.class); + + public static void main(String[] args) { + + String str = "Hello World"; + + try { + char charAtNegativeIndex = str.charAt(-1); // Trying to access at negative index + char charAtLengthIndex = str.charAt(11); // Trying to access at index equal to size of the string + } catch (StringIndexOutOfBoundsException e) { + LOGGER.error("StringIndexOutOfBoundsException caught"); + } + + } + +} diff --git a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/exceptions/GlobalExceptionHandlerUnitTest.java b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/exceptions/GlobalExceptionHandlerUnitTest.java new file mode 100644 index 0000000000..394de9c576 --- /dev/null +++ b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/exceptions/GlobalExceptionHandlerUnitTest.java @@ -0,0 +1,64 @@ +package com.baeldung.exceptions; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.slf4j.LoggerFactory; +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.classic.spi.LoggingEvent; +import ch.qos.logback.core.Appender; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.verify; + +@RunWith(MockitoJUnitRunner.class) +public class GlobalExceptionHandlerUnitTest { + + @Mock + private Appender mockAppender; + + @Captor + private ArgumentCaptor captorLoggingEvent; + + @Before + public void setup() { + final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + logger.addAppender(mockAppender); + + Handler globalExceptionHandler = new Handler(); + Thread.setDefaultUncaughtExceptionHandler(globalExceptionHandler); + } + + @After + public void teardown() { + final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + logger.detachAppender(mockAppender); + } + + @Test + public void whenArithmeticException_thenUseUncaughtExceptionHandler() throws InterruptedException { + + Thread globalExceptionHandlerThread = new Thread() { + public void run() { + GlobalExceptionHandler globalExceptionHandlerObj = new GlobalExceptionHandler(); + globalExceptionHandlerObj.performArithmeticOperation(99, 0); + } + }; + + globalExceptionHandlerThread.start(); + globalExceptionHandlerThread.join(); + + verify(mockAppender).doAppend(captorLoggingEvent.capture()); + LoggingEvent loggingEvent = captorLoggingEvent.getValue(); + + assertThat(loggingEvent.getLevel()).isEqualTo(Level.INFO); + assertThat(loggingEvent.getFormattedMessage()).isEqualTo("Unhandled exception caught!"); + } + +}