BAEL-1921 - added example code and unit test for GlobalExceptionHandler (#4646)

* added example code and unit test for GlobalExceptionHandler

* Code for common exceptions
This commit is contained in:
Mrudav Shukla 2018-07-08 17:41:29 +05:30 committed by mikr
parent 13ce413ed2
commit f56bf16d11
14 changed files with 407 additions and 0 deletions

View File

@ -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!");
}
}
}

View File

@ -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");
}
}
}

View File

@ -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!");
}
}
}

View File

@ -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!");
}
}
}

View File

@ -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!");
}
}

View File

@ -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!");
}
}
}

View File

@ -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<Integer> intList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
intList.add(i);
}
Iterator<Integer> intListIterator = intList.iterator(); // Initialized with index at -1
try {
intListIterator.remove(); // IllegalStateException
} catch (IllegalStateException e) {
LOGGER.error("IllegalStateException caught!");
}
}
}

View File

@ -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();
}
}

View File

@ -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!");
}
}
}

View File

@ -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;
}
}

View File

@ -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!");
}
}
}

View File

@ -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!");
}
}
}

View File

@ -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");
}
}
}

View File

@ -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<ILoggingEvent> mockAppender;
@Captor
private ArgumentCaptor<LoggingEvent> 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!");
}
}