Move articles out of core-java-lang part 1 (#7908)

This commit is contained in:
Catalin Burcea 2019-10-03 07:02:53 +03:00 committed by Josh Cummings
parent aa88f134d3
commit 6cb034c1d8
82 changed files with 128 additions and 1250 deletions

View File

@ -1,8 +1,13 @@
## Relevant Articles:
## Core Java Exceptions
- [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)
This module contains articles about core java exceptions
### Relevant articles:
- [Chained Exceptions in Java](https://www.baeldung.com/java-chained-exceptions)
- [ClassNotFoundException vs NoClassDefFoundError](https://www.baeldung.com/java-classnotfoundexception-and-noclassdeffounderror)
- [Create a Custom Exception in Java](https://www.baeldung.com/java-new-custom-exception)
- [Exception Handling in Java](https://www.baeldung.com/java-exceptions)
- [Differences Between Final, Finally and Finalize in Java](https://www.baeldung.com/java-final-finally-finalize)
- [Difference Between Throw and Throws in Java](https://www.baeldung.com/java-throw-throws)
- [“Sneaky Throws” in Java](https://www.baeldung.com/java-sneaky-throws)
- [The StackOverflowError in Java](https://www.baeldung.com/java-stack-overflow-error)

View File

@ -1,55 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.exception.numberformat</groupId>
<artifactId>core-java-exceptions</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>core-java-exceptions</name>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<groupId>com.baeldung.exceptions</groupId>
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-exceptions</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-exceptions</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<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>
<dependencies>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>${javax.mail.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</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>
<properties>
<javax.mail.version>1.5.0-b01</javax.mail.version>
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>
</project>

View File

@ -1,20 +0,0 @@
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

@ -1,24 +0,0 @@
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

@ -1,43 +0,0 @@
package com.baeldung.exceptions;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class CheckedUncheckedExceptions {
public static void checkedExceptionWithThrows() throws FileNotFoundException {
File file = new File("not_existing_file.txt");
FileInputStream stream = new FileInputStream(file);
}
public static void checkedExceptionWithTryCatch() {
File file = new File("not_existing_file.txt");
try {
FileInputStream stream = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static int divideByZero() {
int numerator = 1;
int denominator = 0;
return numerator / denominator;
}
public static void checkFile(String fileName) throws IncorrectFileNameException {
if (fileName == null || fileName.isEmpty()) {
throw new NullOrEmptyException("The filename is null.");
}
if (!isCorrectFileName(fileName)) {
throw new IncorrectFileNameException("Incorrect filename : " + fileName);
}
}
private static boolean isCorrectFileName(String fileName) {
if (fileName.equals("wrongFileName.txt"))
return false;
else
return true;
}
}

View File

@ -1,36 +0,0 @@
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

@ -1,25 +0,0 @@
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

@ -1,28 +0,0 @@
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

@ -1,18 +0,0 @@
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

@ -1,32 +0,0 @@
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

@ -1,13 +0,0 @@
package com.baeldung.exceptions;
public class IncorrectFileNameException extends Exception {
private static final long serialVersionUID = 1L;
public IncorrectFileNameException(String errorMessage) {
super(errorMessage);
}
public IncorrectFileNameException(String errorMessage, Throwable thr) {
super(errorMessage, thr);
}
}

View File

@ -1,28 +0,0 @@
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

@ -1,25 +0,0 @@
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

@ -1,14 +0,0 @@
package com.baeldung.exceptions;
public class NullOrEmptyException extends RuntimeException {
private static final long serialVersionUID = 1L;
public NullOrEmptyException(String errorMessage) {
super(errorMessage);
}
public NullOrEmptyException(String errorMessage, Throwable thr) {
super(errorMessage, thr);
}
}

View File

@ -1,36 +0,0 @@
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

@ -1,23 +0,0 @@
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

@ -1,25 +0,0 @@
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

@ -1,98 +0,0 @@
package com.baeldung.exceptions;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeParseException;
import java.util.Objects;
/**
* Utility class to find root cause exceptions.
*/
public class RootCauseFinder {
private RootCauseFinder() {
}
public static Throwable findCauseUsingPlainJava(Throwable throwable) {
Objects.requireNonNull(throwable);
Throwable rootCause = throwable;
while (rootCause.getCause() != null && rootCause.getCause() != rootCause) {
rootCause = rootCause.getCause();
}
return rootCause;
}
/**
* Calculates the age of a person from a given date.
*/
static class AgeCalculator {
private AgeCalculator() {
}
public static int calculateAge(String birthDate) {
if (birthDate == null || birthDate.isEmpty()) {
throw new IllegalArgumentException();
}
try {
return Period
.between(parseDate(birthDate), LocalDate.now())
.getYears();
} catch (DateParseException ex) {
throw new CalculationException(ex);
}
}
private static LocalDate parseDate(String birthDateAsString) {
LocalDate birthDate;
try {
birthDate = LocalDate.parse(birthDateAsString);
} catch (DateTimeParseException ex) {
throw new InvalidFormatException(birthDateAsString, ex);
}
if (birthDate.isAfter(LocalDate.now())) {
throw new DateOutOfRangeException(birthDateAsString);
}
return birthDate;
}
}
static class CalculationException extends RuntimeException {
CalculationException(DateParseException ex) {
super(ex);
}
}
static class DateParseException extends RuntimeException {
DateParseException(String input) {
super(input);
}
DateParseException(String input, Throwable thr) {
super(input, thr);
}
}
static class InvalidFormatException extends DateParseException {
InvalidFormatException(String input, Throwable thr) {
super("Invalid date format: " + input, thr);
}
}
static class DateOutOfRangeException extends DateParseException {
DateOutOfRangeException(String date) {
super("Date out of range: " + date);
}
}
}

View File

@ -1,30 +0,0 @@
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

@ -1,23 +0,0 @@
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

@ -1,9 +1,9 @@
package com.baeldung.chainedexception;
package com.baeldung.exceptions.chainedexception;
import com.baeldung.chainedexception.exceptions.GirlFriendOfManagerUpsetException;
import com.baeldung.chainedexception.exceptions.ManagerUpsetException;
import com.baeldung.chainedexception.exceptions.NoLeaveGrantedException;
import com.baeldung.chainedexception.exceptions.TeamLeadUpsetException;
import com.baeldung.exceptions.chainedexception.exceptions.GirlFriendOfManagerUpsetException;
import com.baeldung.exceptions.chainedexception.exceptions.ManagerUpsetException;
import com.baeldung.exceptions.chainedexception.exceptions.NoLeaveGrantedException;
import com.baeldung.exceptions.chainedexception.exceptions.TeamLeadUpsetException;
public class LogWithChain {

View File

@ -1,9 +1,9 @@
package com.baeldung.chainedexception;
package com.baeldung.exceptions.chainedexception;
import com.baeldung.chainedexception.exceptions.GirlFriendOfManagerUpsetException;
import com.baeldung.chainedexception.exceptions.ManagerUpsetException;
import com.baeldung.chainedexception.exceptions.NoLeaveGrantedException;
import com.baeldung.chainedexception.exceptions.TeamLeadUpsetException;
import com.baeldung.exceptions.chainedexception.exceptions.GirlFriendOfManagerUpsetException;
import com.baeldung.exceptions.chainedexception.exceptions.ManagerUpsetException;
import com.baeldung.exceptions.chainedexception.exceptions.NoLeaveGrantedException;
import com.baeldung.exceptions.chainedexception.exceptions.TeamLeadUpsetException;
public class LogWithoutChain {

View File

@ -1,4 +1,4 @@
package com.baeldung.chainedexception.exceptions;
package com.baeldung.exceptions.chainedexception.exceptions;
public class GirlFriendOfManagerUpsetException extends Exception {

View File

@ -1,4 +1,4 @@
package com.baeldung.chainedexception.exceptions;
package com.baeldung.exceptions.chainedexception.exceptions;
public class ManagerUpsetException extends Exception {

View File

@ -1,4 +1,4 @@
package com.baeldung.chainedexception.exceptions;
package com.baeldung.exceptions.chainedexception.exceptions;
public class NoLeaveGrantedException extends Exception {

View File

@ -1,4 +1,4 @@
package com.baeldung.chainedexception.exceptions;
package com.baeldung.exceptions.chainedexception.exceptions;
public class TeamLeadUpsetException extends Exception {

View File

@ -1,4 +1,4 @@
package com.baeldung.customexception;
package com.baeldung.exceptions.customexception;
import java.io.File;
import java.io.FileNotFoundException;

View File

@ -1,4 +1,4 @@
package com.baeldung.customexception;
package com.baeldung.exceptions.customexception;
public class IncorrectFileExtensionException extends RuntimeException{
private static final long serialVersionUID = 1L;

View File

@ -1,4 +1,4 @@
package com.baeldung.customexception;
package com.baeldung.exceptions.customexception;
public class IncorrectFileNameException extends Exception {
private static final long serialVersionUID = 1L;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptionhandling;
package com.baeldung.exceptions.exceptionhandling;
import java.io.File;
import java.io.FileNotFoundException;

View File

@ -0,0 +1,5 @@
package com.baeldung.exceptions.exceptionhandling;
public class MyException extends Throwable {
}

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptionhandling;
package com.baeldung.exceptions.exceptionhandling;
public class Player {

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptionhandling;
package com.baeldung.exceptions.exceptionhandling;
public class PlayerScoreException extends Exception {

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptionhandling;
package com.baeldung.exceptions.exceptionhandling;
public class TimeoutException extends Exception {

View File

@ -1,4 +1,4 @@
package com.baeldung.keywords.finalize;
package com.baeldung.exceptions.keywords.finalize;
public class FinalizeObject {

View File

@ -1,4 +1,4 @@
package com.baeldung.keywords.finalkeyword;
package com.baeldung.exceptions.keywords.finalkeyword;
public final class Child extends Parent {

View File

@ -1,4 +1,4 @@
package com.baeldung.keywords.finalkeyword;
package com.baeldung.exceptions.keywords.finalkeyword;
/*public class GrandChild extends Child {
// Compilation error

View File

@ -1,4 +1,4 @@
package com.baeldung.keywords.finalkeyword;
package com.baeldung.exceptions.keywords.finalkeyword;
public class Parent {

View File

@ -1,4 +1,4 @@
package com.baeldung.keywords.finallykeyword;
package com.baeldung.exceptions.keywords.finallykeyword;
public class FinallyExample {

View File

@ -1,4 +1,4 @@
package com.baeldung.noclassdeffounderror;
package com.baeldung.exceptions.noclassdeffounderror;
public class ClassWithInitErrors {
static int data = 1 / 0;

View File

@ -1,4 +1,4 @@
package com.baeldung.noclassdeffounderror;
package com.baeldung.exceptions.noclassdeffounderror;
public class NoClassDefFoundErrorExample {
public ClassWithInitErrors getClassWithInitErrors() {

View File

@ -1,4 +1,4 @@
package com.baeldung.sneakythrows;
package com.baeldung.exceptions.sneakythrows;
import lombok.SneakyThrows;

View File

@ -1,4 +1,4 @@
package com.baeldung.sneakythrows;
package com.baeldung.exceptions.sneakythrows;
import java.io.IOException;

View File

@ -1,4 +1,4 @@
package com.baeldung.stackoverflowerror;
package com.baeldung.exceptions.stackoverflowerror;
public class AccountHolder {
private String firstName;

View File

@ -1,4 +1,4 @@
package com.baeldung.stackoverflowerror;
package com.baeldung.exceptions.stackoverflowerror;
public class ClassOne {
private int oneValue;

View File

@ -1,4 +1,4 @@
package com.baeldung.stackoverflowerror;
package com.baeldung.exceptions.stackoverflowerror;
public class ClassTwo {
private int twoValue;

View File

@ -1,4 +1,4 @@
package com.baeldung.stackoverflowerror;
package com.baeldung.exceptions.stackoverflowerror;
public class InfiniteRecursionWithTerminationCondition {
public int calculateFactorial(final int number) {

View File

@ -1,4 +1,4 @@
package com.baeldung.stackoverflowerror;
package com.baeldung.exceptions.stackoverflowerror;
public class RecursionWithCorrectTerminationCondition {
public int calculateFactorial(final int number) {

View File

@ -1,4 +1,4 @@
package com.baeldung.stackoverflowerror;
package com.baeldung.exceptions.stackoverflowerror;
public class UnintendedInfiniteRecursion {
public int calculateFactorial(int number) {

View File

@ -1,4 +1,4 @@
package com.baeldung.throwsexception;
package com.baeldung.exceptions.throwvsthrows;
public class DataAccessException extends RuntimeException {

View File

@ -1,4 +1,4 @@
package com.baeldung.throwsexception;
package com.baeldung.exceptions.throwvsthrows;
import com.sun.mail.iap.ConnectionException;

View File

@ -1,4 +1,4 @@
package com.baeldung.throwsexception;
package com.baeldung.exceptions.throwvsthrows;
import java.sql.SQLException;
import java.util.List;

View File

@ -1,4 +1,4 @@
package com.baeldung.throwsexception;
package com.baeldung.exceptions.throwvsthrows;
import java.sql.SQLException;

View File

@ -1,4 +1,4 @@
package com.baeldung.throwsexception;
package com.baeldung.exceptions.throwvsthrows;
import com.sun.mail.iap.ConnectionException;

View File

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

View File

@ -1,25 +0,0 @@
package com.baeldung.exception.error;
import org.junit.Assert;
import org.junit.Test;
public class ErrorGeneratorUnitTest {
@Test(expected = AssertionError.class)
public void whenError_thenIsNotCaughtByCatchException() {
try {
throw new AssertionError();
} catch (Exception e) {
Assert.fail(); // errors are not caught by catch exception
}
}
@Test
public void whenError_thenIsCaughtByCatchError() {
try {
throw new AssertionError();
} catch (Error e) {
// caught! -> test pass
}
}
}

View File

@ -1,154 +0,0 @@
package com.baeldung.exception.numberformat;
import static org.junit.Assert.assertEquals;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import java.util.logging.Logger;
import org.junit.Test;
/**
* A set of examples tested to show cases where NumberFormatException is thrown and not thrown.
*/
public class NumberFormatExceptionUnitTest {
Logger LOG = Logger.getLogger(NumberFormatExceptionUnitTest.class.getName());
/* ---INTEGER FAIL CASES--- */
@Test(expected = NumberFormatException.class)
public void givenByteConstructor_whenAlphabetAsInput_thenFail() {
Byte byteInt = new Byte("one");
}
@Test(expected = NumberFormatException.class)
public void givenShortConstructor_whenSpaceInInput_thenFail() {
Short shortInt = new Short("2 ");
}
@Test(expected = NumberFormatException.class)
public void givenParseIntMethod_whenSpaceInInput_thenFail() {
Integer aIntPrim = Integer.parseInt("6000 ");
}
@Test(expected = NumberFormatException.class)
public void givenParseIntMethod_whenUnderscoreInInput_thenFail() {
int bIntPrim = Integer.parseInt("_6000");
}
@Test(expected = NumberFormatException.class)
public void givenIntegerValueOfMethod_whenCommaInInput_thenFail() {
Integer cIntPrim = Integer.valueOf("6,000");
}
@Test(expected = NumberFormatException.class)
public void givenBigIntegerConstructor_whenDecimalInInput_thenFail() {
BigInteger bigInteger = new BigInteger("4.0");
}
@Test(expected = NumberFormatException.class)
public void givenDecodeMethod_whenAlphabetInInput_thenFail() {
Long decodedLong = Long.decode("64403L");
}
/* ---INTEGER PASS CASES--- */
@Test
public void givenInvalidNumberInputs_whenOptimized_thenPass() {
Byte byteInt = new Byte("1");
assertEquals(1, byteInt.intValue());
Short shortInt = new Short("2 ".trim());
assertEquals(2, shortInt.intValue());
Integer aIntObj = Integer.valueOf("6");
assertEquals(6, aIntObj.intValue());
BigInteger bigInteger = new BigInteger("4");
assertEquals(4, bigInteger.intValue());
int aIntPrim = Integer.parseInt("6000 ".trim());
assertEquals(6000, aIntPrim);
int bIntPrim = Integer.parseInt("_6000".replaceAll("_", ""));
assertEquals(6000, bIntPrim);
int cIntPrim = Integer.parseInt("-6000");
assertEquals(-6000, cIntPrim);
Long decodeInteger = Long.decode("644032334");
assertEquals(644032334L, decodeInteger.longValue());
}
/* ---DOUBLE FAIL CASES--- */
@Test(expected = NumberFormatException.class)
public void givenFloatConstructor_whenAlphabetInInput_thenFail() {
Float floatDecimalObj = new Float("one.1");
}
@Test(expected = NumberFormatException.class)
public void givenDoubleConstructor_whenAlphabetInInput_thenFail() {
Double doubleDecimalObj = new Double("two.2");
}
@Test(expected = NumberFormatException.class)
public void givenBigDecimalConstructor_whenSpecialCharsInInput_thenFail() {
BigDecimal bigDecimalObj = new BigDecimal("3_0.3");
}
@Test(expected = NumberFormatException.class)
public void givenParseDoubleMethod_whenCommaInInput_thenFail() {
double aDoublePrim = Double.parseDouble("4000,1");
}
/* ---DOUBLE PASS CASES--- */
@Test
public void givenDoubleConstructor_whenDecimalInInput_thenPass() {
Double doubleDecimalObj = new Double("2.2");
assertEquals(2.2, doubleDecimalObj.doubleValue(), 0);
}
@Test
public void givenDoubleValueOfMethod_whenMinusInInput_thenPass() {
Double aDoubleObj = Double.valueOf("-6000");
assertEquals(-6000, aDoubleObj.doubleValue(), 0);
}
@Test
public void givenUsDecimalNumber_whenParsedWithNumberFormat_thenPass() throws ParseException {
Number parsedNumber = parseNumberWithLocale("4000.1", Locale.US);
assertEquals(4000.1, parsedNumber);
assertEquals(4000.1, parsedNumber.doubleValue(), 0);
assertEquals(4000, parsedNumber.intValue());
}
/**
* In most European countries (for example, France), comma is used as decimal in place of period.
* @throws ParseException if the input string contains special characters other than comma or decimal.
* In this test case, anything after decimal (period) is dropped when a European locale is set.
*/
@Test
public void givenEuDecimalNumberHasComma_whenParsedWithNumberFormat_thenPass() throws ParseException {
Number parsedNumber = parseNumberWithLocale("4000,1", Locale.FRANCE);
LOG.info("Number parsed is: " + parsedNumber);
assertEquals(4000.1, parsedNumber);
assertEquals(4000.1, parsedNumber.doubleValue(), 0);
assertEquals(4000, parsedNumber.intValue());
}
/**
* Converts a string into a number retaining all decimals, and symbols valid in a locale.
* @param number the input string for a number.
* @param locale the locale to consider while parsing a number.
* @return the generic number object which can represent multiple number types.
* @throws ParseException when input contains invalid characters.
*/
private Number parseNumberWithLocale(String number, Locale locale) throws ParseException {
locale = locale == null ? Locale.getDefault() : locale;
NumberFormat numberFormat = NumberFormat.getInstance(locale);
return numberFormat.parse(number);
}
}

View File

@ -1,55 +0,0 @@
package com.baeldung.exceptions;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.FileNotFoundException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* Tests the {@link CheckedUncheckedExceptions}.
*/
public class CheckedUncheckedExceptionsUnitTest {
@Test
public void whenFileNotExist_thenThrowException() {
assertThrows(FileNotFoundException.class, () -> {
CheckedUncheckedExceptions.checkedExceptionWithThrows();
});
}
@Test
public void whenTryCatchExcetpion_thenSuccess() {
try {
CheckedUncheckedExceptions.checkedExceptionWithTryCatch();
} catch (Exception e) {
Assertions.fail(e.getMessage());
}
}
@Test
public void whenDivideByZero_thenThrowException() {
assertThrows(ArithmeticException.class, () -> {
CheckedUncheckedExceptions.divideByZero();
});
}
@Test
public void whenInvalidFile_thenThrowException() {
assertThrows(IncorrectFileNameException.class, () -> {
CheckedUncheckedExceptions.checkFile("wrongFileName.txt");
});
}
@Test
public void whenNullOrEmptyFile_thenThrowException() {
assertThrows(NullOrEmptyException.class, () -> {
CheckedUncheckedExceptions.checkFile(null);
});
assertThrows(NullOrEmptyException.class, () -> {
CheckedUncheckedExceptions.checkFile("");
});
}
}

View File

@ -1,64 +0,0 @@
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

@ -1,114 +0,0 @@
package com.baeldung.exceptions;
import com.google.common.base.Throwables;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import static com.baeldung.exceptions.RootCauseFinder.*;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests the {@link RootCauseFinder}.
*/
public class RootCauseFinderUnitTest {
@Test
public void givenBirthDate_whenCalculatingAge_thenAgeReturned() {
try {
int age = AgeCalculator.calculateAge("1990-01-01");
Assertions.assertEquals(1990, LocalDate
.now()
.minus(age, ChronoUnit.YEARS)
.getYear());
} catch (CalculationException e) {
Assertions.fail(e.getMessage());
}
}
@Test
public void givenWrongFormatDate_whenFindingRootCauseUsingJava_thenRootCauseFound() {
try {
AgeCalculator.calculateAge("010102");
} catch (CalculationException ex) {
assertTrue(findCauseUsingPlainJava(ex) instanceof DateTimeParseException);
}
}
@Test
public void givenOutOfRangeDate_whenFindingRootCauseUsingJava_thenRootCauseFound() {
try {
AgeCalculator.calculateAge("2020-04-04");
} catch (CalculationException ex) {
assertTrue(findCauseUsingPlainJava(ex) instanceof DateOutOfRangeException);
}
}
@Test
public void givenNullDate_whenFindingRootCauseUsingJava_thenRootCauseFound() {
try {
AgeCalculator.calculateAge(null);
} catch (Exception ex) {
assertTrue(findCauseUsingPlainJava(ex) instanceof IllegalArgumentException);
}
}
@Test
public void givenWrongFormatDate_whenFindingRootCauseUsingApacheCommons_thenRootCauseFound() {
try {
AgeCalculator.calculateAge("010102");
} catch (CalculationException ex) {
assertTrue(ExceptionUtils.getRootCause(ex) instanceof DateTimeParseException);
}
}
@Test
public void givenOutOfRangeDate_whenFindingRootCauseUsingApacheCommons_thenRootCauseFound() {
try {
AgeCalculator.calculateAge("2020-04-04");
} catch (CalculationException ex) {
assertTrue(ExceptionUtils.getRootCause(ex) instanceof DateOutOfRangeException);
}
}
@Test
public void givenNullDate_whenFindingRootCauseUsingApacheCommons_thenRootCauseNotFound() {
try {
AgeCalculator.calculateAge(null);
} catch (Exception ex) {
assertTrue(ExceptionUtils.getRootCause(ex) instanceof IllegalArgumentException);
}
}
@Test
public void givenWrongFormatDate_whenFindingRootCauseUsingGuava_thenRootCauseFound() {
try {
AgeCalculator.calculateAge("010102");
} catch (CalculationException ex) {
assertTrue(Throwables.getRootCause(ex) instanceof DateTimeParseException);
}
}
@Test
public void givenOutOfRangeDate_whenFindingRootCauseUsingGuava_thenRootCauseFound() {
try {
AgeCalculator.calculateAge("2020-04-04");
} catch (CalculationException ex) {
assertTrue(Throwables.getRootCause(ex) instanceof DateOutOfRangeException);
}
}
@Test
public void givenNullDate_whenFindingRootCauseUsingGuava_thenRootCauseFound() {
try {
AgeCalculator.calculateAge(null);
} catch (Exception ex) {
assertTrue(Throwables.getRootCause(ex) instanceof IllegalArgumentException);
}
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.customexception;
package com.baeldung.exceptions.customexception;
import static org.assertj.core.api.Assertions.assertThat;

View File

@ -1,4 +1,4 @@
package com.baeldung.customexception;
package com.baeldung.exceptions.customexception;
import static org.assertj.core.api.Assertions.assertThat;

View File

@ -1,4 +1,4 @@
package com.baeldung.throwsexception;
package com.baeldung.exceptions.throwvsthrows;
import org.junit.jupiter.api.Test;

View File

@ -1,92 +0,0 @@
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

@ -1,43 +0,0 @@
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);
}
}

View File

@ -4,30 +4,22 @@
### Relevant Articles:
- [Generate equals() and hashCode() with Eclipse](http://www.baeldung.com/java-eclipse-equals-and-hashcode)
- [Chained Exceptions in Java](http://www.baeldung.com/java-chained-exceptions)
- [Iterating Over Enum Values in Java](http://www.baeldung.com/java-enum-iteration)
- [Java Double Brace Initialization](http://www.baeldung.com/java-double-brace-initialization)
- [Guide to the Diamond Operator in Java](http://www.baeldung.com/java-diamond-operator)
- [Comparator and Comparable in Java](http://www.baeldung.com/java-comparator-comparable)
- [The Java continue and break Keywords](http://www.baeldung.com/java-continue-and-break)
- [Nested Classes in Java](http://www.baeldung.com/java-nested-classes)
- [A Guide to Inner Interfaces in Java](http://www.baeldung.com/java-inner-interfaces)
- [Recursion In Java](http://www.baeldung.com/java-recursion)
- [A Guide to the finalize Method in Java](http://www.baeldung.com/java-finalize)
- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java)
- [Quick Guide to java.lang.System](http://www.baeldung.com/java-lang-system)
- [Using Java Assertions](http://www.baeldung.com/java-assert)
- [ClassNotFoundException vs NoClassDefFoundError](http://www.baeldung.com/java-classnotfoundexception-and-noclassdeffounderror)
- [The StackOverflowError in Java](http://www.baeldung.com/java-stack-overflow-error)
- [Create a Custom Exception in Java](http://www.baeldung.com/java-new-custom-exception)
- [Exception Handling in Java](http://www.baeldung.com/java-exceptions)
- [Differences Between Final, Finally and Finalize in Java](https://www.baeldung.com/java-final-finally-finalize)
- [Generate equals() and hashCode() with Eclipse](https://www.baeldung.com/java-eclipse-equals-and-hashcode)
- [Iterating Over Enum Values in Java](https://www.baeldung.com/java-enum-iteration)
- [Java Double Brace Initialization](https://www.baeldung.com/java-double-brace-initialization)
- [Guide to the Diamond Operator in Java](https://www.baeldung.com/java-diamond-operator)
- [Comparator and Comparable in Java](https://www.baeldung.com/java-comparator-comparable)
- [The Java continue and break Keywords](https://www.baeldung.com/java-continue-and-break)
- [Nested Classes in Java](https://www.baeldung.com/java-nested-classes)
- [A Guide to Inner Interfaces in Java](https://www.baeldung.com/java-inner-interfaces)
- [Recursion In Java](https://www.baeldung.com/java-recursion)
- [A Guide to the finalize Method in Java](https://www.baeldung.com/java-finalize)
- [Infinite Loops in Java](https://www.baeldung.com/infinite-loops-java)
- [Quick Guide to java.lang.System](https://www.baeldung.com/java-lang-system)
- [Using Java Assertions](https://www.baeldung.com/java-assert)
- [Static and Dynamic Binding in Java](https://www.baeldung.com/java-static-dynamic-binding)
- [Difference Between Throw and Throws in Java](https://www.baeldung.com/java-throw-throws)
- [Synthetic Constructs in Java](https://www.baeldung.com/java-synthetic)
- [How to Separate Double into Integer and Decimal Parts](https://www.baeldung.com/java-separate-double-into-integer-decimal-parts)
- [“Sneaky Throws” in Java](http://www.baeldung.com/java-sneaky-throws)
- [Retrieving a Class Name in Java](https://www.baeldung.com/java-class-name)
- [Java Compound Operators](https://www.baeldung.com/java-compound-operators)
- [Guide to Java Packages](https://www.baeldung.com/java-packages)

View File

@ -43,12 +43,6 @@
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
@ -56,11 +50,6 @@
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>${javax.mail.version}</version>
</dependency>
</dependencies>
<build>
@ -75,9 +64,6 @@
<properties>
<gson.version>2.8.2</gson.version>
<javax.mail.version>1.5.0-b01</javax.mail.version>
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
</properties>

View File

@ -1,5 +0,0 @@
package com.baeldung.exceptionhandling;
public class MyException extends Throwable {
}

View File

@ -15,7 +15,6 @@
<modules>
<module>pre-jpms</module>
<module>core-java-exceptions</module>
<module>core-java-optional</module>
<module>core-java-lang-operators</module>
<module>core-java-networking-2</module>

View File

@ -415,6 +415,7 @@
<module>core-java-modules/core-java-io-files</module>
<module>core-java-modules/core-java-nio</module>
<module>core-java-modules/core-java-security</module>
<module>core-java-modules/core-java-exceptions</module>
<module>core-java-modules/core-java-lang-syntax</module>
<module>core-java-modules/core-java-lang-syntax-2</module>
<module>core-java-modules/core-java-lang</module>
@ -1162,6 +1163,7 @@
<module>core-java-modules/core-java-io-files</module>
<module>core-java-modules/core-java-nio</module>
<module>core-java-modules/core-java-security</module>
<module>core-java-modules/core-java-exceptions</module>
<module>core-java-modules/core-java-lang-syntax</module>
<module>core-java-modules/core-java-lang-syntax-2</module>
<module>core-java-modules/core-java-lang</module>