[BAEL-13505] Move articles out of core-java part 1

This commit is contained in:
Sjmillington
2019-09-05 17:44:52 +01:00
parent 434bfc980e
commit 3e155818d5
36 changed files with 28 additions and 0 deletions

View File

@@ -1,3 +1,8 @@
## Relevant Articles:
- [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch)
- [Java Global Exception Handler](http://www.baeldung.com/java-global-exception-handler)
- [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions)
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
- [How to Find an Exceptions Root Cause in Java](https://www.baeldung.com/java-exception-root-cause)
- [Java Try with Resources](https://www.baeldung.com/java-try-with-resources)

View File

@@ -26,10 +26,30 @@
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator-annprocess.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<commons-lang3.version>3.9</commons-lang3.version>
<jmh-core.version>1.19</jmh-core.version>
<assertj-core.version>3.10.0</assertj-core.version>
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
</properties>
</project>

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,30 @@
package com.baeldung.exceptions;
import org.apache.commons.lang3.exception.ExceptionUtils;
import java.io.PrintWriter;
import java.io.StringWriter;
public class StackTraceToString {
public static void main(String[] args) {
// Convert a StackTrace to String using core java
try {
throw new NullPointerException();
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
System.out.println(sw.toString());
}
// Convert a StackTrace to String using Apache Commons
try {
throw new IndexOutOfBoundsException();
} catch (Exception e) {
System.out.println(ExceptionUtils.getStackTrace(e));
}
}
}

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,13 @@
package com.baeldung.optional;
public class Modem {
private Double price;
public Modem(Double price) {
this.price = price;
}
public Double getPrice() {
return price;
}
}

View File

@@ -0,0 +1,34 @@
package com.baeldung.optional;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OrElseAndOrElseGet {
public static List<String> names = Arrays.asList("John", "Jones", "Kelly", "Cristina", "Raven");
private static final Logger LOG = LoggerFactory.getLogger(OrElseAndOrElseGet.class);
public String getRandomName() {
LOG.info("getRandomName() method - start");
Random random = new Random();
int index = random.nextInt(5);
LOG.info("getRandomName() method - end");
return names.get(index);
}
public String getNameUsingOrElse(String name) {
return Optional.ofNullable(name)
.orElse(getRandomName());
}
public String getNameUsingOrElseGet(String name) {
return Optional.ofNullable(name)
.orElseGet(() -> getRandomName());
}
}

View File

@@ -0,0 +1,37 @@
package com.baeldung.optional;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.RunnerException;
@Fork(1)
@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class OrElseAndOrElseGetBenchmarkRunner {
private OrElseAndOrElseGet orElsevsOrElseGet = new OrElseAndOrElseGet();
public static void main(String[] args) throws RunnerException, IOException {
org.openjdk.jmh.Main.main(args);
}
@Benchmark
public String orElseBenchmark() {
return orElsevsOrElseGet.getNameUsingOrElse("baeldung");
}
@Benchmark
public String orElseGetBenchmark() {
return orElsevsOrElseGet.getNameUsingOrElseGet("baeldung");
}
}

View File

@@ -0,0 +1,39 @@
package com.baeldung.optional;
import java.util.Optional;
public class Person {
private String name;
private int age;
private String password;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Optional<String> getName() {
return Optional.ofNullable(name);
}
public void setName(String name) {
this.name = name;
}
public Optional<Integer> getAge() {
return Optional.ofNullable(age);
}
public void setAge(int age) {
this.age = age;
}
public void setPassword(String password) {
this.password = password;
}
public Optional<String> getPassword() {
return Optional.ofNullable(password);
}
}

View File

@@ -0,0 +1,9 @@
package com.baeldung.optional;
public class PersonRepository {
public String findNameById(String id) {
return id == null ? null : "Name";
}
}

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

View File

@@ -0,0 +1,92 @@
package com.baeldung.java8;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.Scanner;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JavaTryWithResourcesLongRunningUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(JavaTryWithResourcesLongRunningUnitTest.class);
private static final String TEST_STRING_HELLO_WORLD = "Hello World";
private Date resource1Date, resource2Date;
// tests
/* Example for using Try_with_resources */
@Test
public void whenWritingToStringWriter_thenCorrectlyWritten() {
final StringWriter sw = new StringWriter();
try (PrintWriter pw = new PrintWriter(sw, true)) {
pw.print(TEST_STRING_HELLO_WORLD);
}
Assert.assertEquals(sw.getBuffer()
.toString(), TEST_STRING_HELLO_WORLD);
}
/* Example for using multiple resources */
@Test
public void givenStringToScanner_whenWritingToStringWriter_thenCorrectlyWritten() {
final StringWriter sw = new StringWriter();
try (Scanner sc = new Scanner(TEST_STRING_HELLO_WORLD); PrintWriter pw = new PrintWriter(sw, true)) {
while (sc.hasNext()) {
pw.print(sc.nextLine());
}
}
Assert.assertEquals(sw.getBuffer()
.toString(), TEST_STRING_HELLO_WORLD);
}
/* Example to show order in which the resources are closed */
@Test
public void whenFirstAutoClosableResourceIsinitializedFirst_thenFirstAutoClosableResourceIsReleasedFirst() throws Exception {
try (AutoCloseableResourcesFirst af = new AutoCloseableResourcesFirst(); AutoCloseableResourcesSecond as = new AutoCloseableResourcesSecond()) {
af.doSomething();
as.doSomething();
}
Assert.assertTrue(resource1Date.after(resource2Date));
}
class AutoCloseableResourcesFirst implements AutoCloseable {
public AutoCloseableResourcesFirst() {
LOG.debug("Constructor -> AutoCloseableResources_First");
}
public void doSomething() {
LOG.debug("Something -> AutoCloseableResources_First");
}
@Override
public void close() throws Exception {
LOG.debug("Closed AutoCloseableResources_First");
resource1Date = new Date();
}
}
class AutoCloseableResourcesSecond implements AutoCloseable {
public AutoCloseableResourcesSecond() {
LOG.debug("Constructor -> AutoCloseableResources_Second");
}
public void doSomething() {
LOG.debug("Something -> AutoCloseableResources_Second");
}
@Override
public void close() throws Exception {
LOG.debug("Closed AutoCloseableResources_Second");
resource2Date = new Date();
Thread.sleep(10000);
}
}
}

View File

@@ -0,0 +1,43 @@
package com.baeldung.optional;
import org.junit.Test;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class PersonRepositoryUnitTest {
PersonRepository personRepository = new PersonRepository();
@Test
public void whenIdIsNull_thenExceptionIsThrown() {
assertThrows(IllegalArgumentException.class,
() ->
Optional
.ofNullable(personRepository.findNameById(null))
.orElseThrow(IllegalArgumentException::new));
}
@Test
public void whenIdIsNonNull_thenNoExceptionIsThrown() {
assertAll(
() ->
Optional
.ofNullable(personRepository.findNameById("id"))
.orElseThrow(RuntimeException::new));
}
@Test
public void whenIdNonNull_thenReturnsNameUpperCase() {
String name = Optional
.ofNullable(personRepository.findNameById("id"))
.map(String::toUpperCase)
.orElseThrow(RuntimeException::new);
assertEquals("NAME", name);
}
}