Move articles out of core-java-lang part 1 (#7908)
This commit is contained in:
committed by
Josh Cummings
parent
aa88f134d3
commit
6cb034c1d8
@@ -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 Exception’s 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)
|
||||
|
||||
@@ -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>
|
||||
@@ -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!");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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!");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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!");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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!");
|
||||
}
|
||||
}
|
||||
@@ -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!");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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!");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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!");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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!");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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!");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.exceptions.chainedexception;
|
||||
|
||||
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 {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
getLeave();
|
||||
}
|
||||
|
||||
private static void getLeave() throws NoLeaveGrantedException {
|
||||
try {
|
||||
howIsTeamLead();
|
||||
} catch (TeamLeadUpsetException e) {
|
||||
throw new NoLeaveGrantedException("Leave not sanctioned.", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void howIsTeamLead() throws TeamLeadUpsetException {
|
||||
try {
|
||||
howIsManager();
|
||||
} catch (ManagerUpsetException e) {
|
||||
throw new TeamLeadUpsetException("Team lead is not in good mood", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void howIsManager() throws ManagerUpsetException {
|
||||
try {
|
||||
howIsGirlFriendOfManager();
|
||||
} catch (GirlFriendOfManagerUpsetException e) {
|
||||
throw new ManagerUpsetException("Manager is in bad mood", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void howIsGirlFriendOfManager() throws GirlFriendOfManagerUpsetException {
|
||||
throw new GirlFriendOfManagerUpsetException("Girl friend of manager is in bad mood");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.exceptions.chainedexception;
|
||||
|
||||
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 {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
getLeave();
|
||||
}
|
||||
|
||||
private static void getLeave() throws NoLeaveGrantedException {
|
||||
try {
|
||||
howIsTeamLead();
|
||||
} catch (TeamLeadUpsetException e) {
|
||||
e.printStackTrace();
|
||||
throw new NoLeaveGrantedException("Leave not sanctioned.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void howIsTeamLead() throws TeamLeadUpsetException {
|
||||
try {
|
||||
howIsManager();
|
||||
} catch (ManagerUpsetException e) {
|
||||
e.printStackTrace();
|
||||
throw new TeamLeadUpsetException("Team lead is not in good mood");
|
||||
}
|
||||
}
|
||||
|
||||
private static void howIsManager() throws ManagerUpsetException {
|
||||
try {
|
||||
howIsGirlFriendOfManager();
|
||||
} catch (GirlFriendOfManagerUpsetException e) {
|
||||
e.printStackTrace();
|
||||
throw new ManagerUpsetException("Manager is in bad mood");
|
||||
}
|
||||
}
|
||||
|
||||
private static void howIsGirlFriendOfManager() throws GirlFriendOfManagerUpsetException {
|
||||
throw new GirlFriendOfManagerUpsetException("Girl friend of manager is in bad mood");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.exceptions.chainedexception.exceptions;
|
||||
|
||||
public class GirlFriendOfManagerUpsetException extends Exception {
|
||||
|
||||
public GirlFriendOfManagerUpsetException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public GirlFriendOfManagerUpsetException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.exceptions.chainedexception.exceptions;
|
||||
|
||||
public class ManagerUpsetException extends Exception {
|
||||
|
||||
public ManagerUpsetException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public ManagerUpsetException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.exceptions.chainedexception.exceptions;
|
||||
|
||||
public class NoLeaveGrantedException extends Exception {
|
||||
|
||||
public NoLeaveGrantedException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public NoLeaveGrantedException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.exceptions.chainedexception.exceptions;
|
||||
|
||||
public class TeamLeadUpsetException extends Exception {
|
||||
|
||||
public TeamLeadUpsetException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public TeamLeadUpsetException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.exceptions.customexception;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class FileManager {
|
||||
|
||||
public static String getFirstLine(String fileName) throws IncorrectFileNameException {
|
||||
try (Scanner file = new Scanner(new File(fileName))) {
|
||||
if (file.hasNextLine()) {
|
||||
return file.nextLine();
|
||||
} else {
|
||||
throw new IllegalArgumentException("Non readable file");
|
||||
}
|
||||
} catch (FileNotFoundException err) {
|
||||
if (!isCorrectFileName(fileName)) {
|
||||
throw new IncorrectFileNameException("Incorrect filename : " + fileName, err);
|
||||
}
|
||||
// Logging etc
|
||||
} catch (IllegalArgumentException err) {
|
||||
if (!containsExtension(fileName)) {
|
||||
throw new IncorrectFileExtensionException("Filename does not contain extension : " + fileName, err);
|
||||
}
|
||||
// Other error cases and logging
|
||||
}
|
||||
return "Default First Line";
|
||||
}
|
||||
|
||||
private static boolean containsExtension(String fileName) {
|
||||
if (fileName.contains(".txt") || fileName.contains(".doc"))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean isCorrectFileName(String fileName) {
|
||||
if (fileName.equals("wrongFileName.txt"))
|
||||
return false;
|
||||
else
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.exceptions.customexception;
|
||||
|
||||
public class IncorrectFileExtensionException extends RuntimeException{
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public IncorrectFileExtensionException(String errorMessage, Throwable err) {
|
||||
super(errorMessage, err);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,9 @@
|
||||
package com.baeldung.exceptions;
|
||||
package com.baeldung.exceptions.customexception;
|
||||
|
||||
public class IncorrectFileNameException extends Exception {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public IncorrectFileNameException(String errorMessage) {
|
||||
super(errorMessage);
|
||||
|
||||
public IncorrectFileNameException(String errorMessage, Throwable err) {
|
||||
super(errorMessage, err);
|
||||
}
|
||||
|
||||
public IncorrectFileNameException(String errorMessage, Throwable thr) {
|
||||
super(errorMessage, thr);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package com.baeldung.exceptions.exceptionhandling;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class Exceptions {
|
||||
|
||||
private final static Logger logger = Logger.getLogger("ExceptionLogging");
|
||||
|
||||
public static List<Player> getPlayers() throws IOException {
|
||||
Path path = Paths.get("players.dat");
|
||||
List<String> players = Files.readAllLines(path);
|
||||
|
||||
return players.stream()
|
||||
.map(Player::new)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public List<Player> loadAllPlayers(String playersFile) throws IOException{
|
||||
try {
|
||||
throw new IOException();
|
||||
} catch(IOException ex) {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreThrows(String playerFile) throws FileNotFoundException {
|
||||
Scanner contents = new Scanner(new File(playerFile));
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
}
|
||||
|
||||
public int getPlayerScoreTryCatch(String playerFile) {
|
||||
try {
|
||||
Scanner contents = new Scanner(new File(playerFile));
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} catch (FileNotFoundException noFile) {
|
||||
throw new IllegalArgumentException("File not found");
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreTryCatchRecovery(String playerFile) {
|
||||
try {
|
||||
Scanner contents = new Scanner(new File(playerFile));
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} catch ( FileNotFoundException noFile ) {
|
||||
logger.warning("File not found, resetting score.");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreFinally(String playerFile) throws FileNotFoundException {
|
||||
Scanner contents = null;
|
||||
try {
|
||||
contents = new Scanner(new File(playerFile));
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} finally {
|
||||
if (contents != null) {
|
||||
contents.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreTryWithResources(String playerFile) {
|
||||
try (Scanner contents = new Scanner(new File(playerFile))) {
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} catch (FileNotFoundException e ) {
|
||||
logger.warning("File not found, resetting score.");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreMultipleCatchBlocks(String playerFile) {
|
||||
try (Scanner contents = new Scanner(new File(playerFile))) {
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} catch (IOException e) {
|
||||
logger.warning("Player file wouldn't load!");
|
||||
return 0;
|
||||
} catch (NumberFormatException e) {
|
||||
logger.warning("Player file was corrupted!");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreMultipleCatchBlocksAlternative(String playerFile) {
|
||||
try (Scanner contents = new Scanner(new File(playerFile)) ) {
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} catch (FileNotFoundException e) {
|
||||
logger.warning("Player file not found!");
|
||||
return 0;
|
||||
} catch (IOException e) {
|
||||
logger.warning("Player file wouldn't load!");
|
||||
return 0;
|
||||
} catch (NumberFormatException e) {
|
||||
logger.warning("Player file was corrupted!");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreUnionCatchBlocks(String playerFile) {
|
||||
try (Scanner contents = new Scanner(new File(playerFile))) {
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} catch (IOException | NumberFormatException e) {
|
||||
logger.warning("Failed to load score!");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public List<Player> loadAllPlayersThrowingChecked(String playersFile) throws TimeoutException {
|
||||
boolean tooLong = true;
|
||||
|
||||
while (!tooLong) {
|
||||
// ... potentially long operation
|
||||
}
|
||||
throw new TimeoutException("This operation took too long");
|
||||
}
|
||||
|
||||
public List<Player> loadAllPlayersThrowingUnchecked(String playersFile) throws TimeoutException {
|
||||
if(!isFilenameValid(playersFile)) {
|
||||
throw new IllegalArgumentException("Filename isn't valid!");
|
||||
}
|
||||
return null;
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
public List<Player> loadAllPlayersWrapping(String playersFile) throws IOException {
|
||||
try {
|
||||
throw new IOException();
|
||||
} catch (IOException io) {
|
||||
throw io;
|
||||
}
|
||||
}
|
||||
|
||||
public List<Player> loadAllPlayersRethrowing(String playersFile) throws PlayerLoadException {
|
||||
try {
|
||||
throw new IOException();
|
||||
} catch (IOException io) {
|
||||
throw new PlayerLoadException(io);
|
||||
}
|
||||
}
|
||||
|
||||
public List<Player> loadAllPlayersThrowable(String playersFile) {
|
||||
try {
|
||||
throw new NullPointerException();
|
||||
} catch ( Throwable t ) {
|
||||
throw t;
|
||||
}
|
||||
}
|
||||
|
||||
class FewerExceptions extends Exceptions {
|
||||
@Override
|
||||
public List<Player> loadAllPlayers(String playersFile) { //can't add "throws MyCheckedException
|
||||
return null;
|
||||
// overridden
|
||||
}
|
||||
}
|
||||
|
||||
public void throwAsGotoAntiPattern() throws MyException {
|
||||
try {
|
||||
// bunch of code
|
||||
throw new MyException();
|
||||
// second bunch of code
|
||||
} catch ( MyException e ) {
|
||||
// third bunch of code
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreSwallowingExceptionAntiPattern(String playerFile) {
|
||||
try {
|
||||
// ...
|
||||
} catch (Exception e) {} // <== catch and swallow
|
||||
return 0;
|
||||
}
|
||||
|
||||
public int getPlayerScoreSwallowingExceptionAntiPatternAlternative(String playerFile) {
|
||||
try {
|
||||
// ...
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public int getPlayerScoreSwallowingExceptionAntiPatternAlternative2(String playerFile) throws PlayerScoreException {
|
||||
try {
|
||||
throw new IOException();
|
||||
} catch (IOException e) {
|
||||
throw new PlayerScoreException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreReturnInFinallyAntiPattern(String playerFile) {
|
||||
int score = 0;
|
||||
try {
|
||||
throw new IOException();
|
||||
} finally {
|
||||
return score; // <== the IOException is dropped
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isFilenameValid(String name) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.exceptions.exceptionhandling;
|
||||
|
||||
public class MyException extends Throwable {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.exceptions.exceptionhandling;
|
||||
|
||||
public class Player {
|
||||
|
||||
public int id;
|
||||
public String name;
|
||||
|
||||
public Player(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.exceptions.exceptionhandling;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class PlayerLoadException extends Exception {
|
||||
|
||||
public PlayerLoadException(IOException io) {
|
||||
super(io);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.exceptions.exceptionhandling;
|
||||
|
||||
public class PlayerScoreException extends Exception {
|
||||
|
||||
public PlayerScoreException(Exception e) {
|
||||
super(e);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.exceptions.exceptionhandling;
|
||||
|
||||
public class TimeoutException extends Exception {
|
||||
|
||||
public TimeoutException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.exceptions.keywords.finalize;
|
||||
|
||||
public class FinalizeObject {
|
||||
|
||||
@Override
|
||||
protected void finalize() throws Throwable {
|
||||
System.out.println("Execute finalize method");
|
||||
super.finalize();
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
FinalizeObject object = new FinalizeObject();
|
||||
object = null;
|
||||
System.gc();
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.exceptions.keywords.finalkeyword;
|
||||
|
||||
public final class Child extends Parent {
|
||||
|
||||
@Override
|
||||
void method1(int arg1, final int arg2) {
|
||||
// OK
|
||||
}
|
||||
|
||||
/* @Override
|
||||
void method2() {
|
||||
// Compilation error
|
||||
}*/
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.exceptions.keywords.finalkeyword;
|
||||
|
||||
/*public class GrandChild extends Child {
|
||||
// Compilation error
|
||||
}*/
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.exceptions.keywords.finalkeyword;
|
||||
|
||||
public class Parent {
|
||||
|
||||
int field1 = 1;
|
||||
final int field2 = 2;
|
||||
|
||||
Parent() {
|
||||
field1 = 2; // OK
|
||||
// field2 = 3; // Compilation error
|
||||
}
|
||||
|
||||
void method1(int arg1, final int arg2) {
|
||||
arg1 = 2; // OK
|
||||
// arg2 = 3; // Compilation error
|
||||
}
|
||||
|
||||
final void method2() {
|
||||
final int localVar = 2; // OK
|
||||
// localVar = 3; // Compilation error
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.exceptions.keywords.finallykeyword;
|
||||
|
||||
public class FinallyExample {
|
||||
|
||||
public static void main(String args[]) throws Exception {
|
||||
try {
|
||||
System.out.println("Execute try block");
|
||||
throw new Exception();
|
||||
} catch (Exception e) {
|
||||
System.out.println("Execute catch block");
|
||||
} finally {
|
||||
System.out.println("Execute finally block");
|
||||
}
|
||||
|
||||
try {
|
||||
System.out.println("Execute try block");
|
||||
} finally {
|
||||
System.out.println("Execute finally block");
|
||||
}
|
||||
|
||||
try {
|
||||
System.out.println("Execute try block");
|
||||
throw new Exception();
|
||||
} finally {
|
||||
System.out.println("Execute finally block");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.exceptions.noclassdeffounderror;
|
||||
|
||||
public class ClassWithInitErrors {
|
||||
static int data = 1 / 0;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.exceptions.noclassdeffounderror;
|
||||
|
||||
public class NoClassDefFoundErrorExample {
|
||||
public ClassWithInitErrors getClassWithInitErrors() {
|
||||
ClassWithInitErrors test;
|
||||
try {
|
||||
test = new ClassWithInitErrors();
|
||||
} catch (Throwable t) {
|
||||
System.out.println(t);
|
||||
}
|
||||
test = new ClassWithInitErrors();
|
||||
return test;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.exceptions.sneakythrows;
|
||||
|
||||
import lombok.SneakyThrows;
|
||||
|
||||
public class SneakyRunnable implements Runnable {
|
||||
|
||||
@SneakyThrows
|
||||
public void run() {
|
||||
try {
|
||||
throw new InterruptedException();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
new SneakyRunnable().run();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.exceptions.sneakythrows;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class SneakyThrows {
|
||||
|
||||
|
||||
public static <E extends Throwable> void sneakyThrow(Throwable e) throws E {
|
||||
throw (E) e;
|
||||
}
|
||||
|
||||
public static void throwsSneakyIOException() {
|
||||
sneakyThrow(new IOException("sneaky"));
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
throwsSneakyIOException();
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.exceptions.stackoverflowerror;
|
||||
|
||||
public class AccountHolder {
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
AccountHolder jointAccountHolder = new AccountHolder();
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.exceptions.stackoverflowerror;
|
||||
|
||||
public class ClassOne {
|
||||
private int oneValue;
|
||||
private ClassTwo clsTwoInstance = null;
|
||||
|
||||
public ClassOne() {
|
||||
oneValue = 0;
|
||||
clsTwoInstance = new ClassTwo();
|
||||
}
|
||||
|
||||
public ClassOne(int oneValue, ClassTwo clsTwoInstance) {
|
||||
this.oneValue = oneValue;
|
||||
this.clsTwoInstance = clsTwoInstance;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.exceptions.stackoverflowerror;
|
||||
|
||||
public class ClassTwo {
|
||||
private int twoValue;
|
||||
private ClassOne clsOneInstance = null;
|
||||
|
||||
public ClassTwo() {
|
||||
twoValue = 10;
|
||||
clsOneInstance = new ClassOne();
|
||||
}
|
||||
|
||||
public ClassTwo(int twoValue, ClassOne clsOneInstance) {
|
||||
this.twoValue = twoValue;
|
||||
this.clsOneInstance = clsOneInstance;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.exceptions.stackoverflowerror;
|
||||
|
||||
public class InfiniteRecursionWithTerminationCondition {
|
||||
public int calculateFactorial(final int number) {
|
||||
return number == 1 ? 1 : number * calculateFactorial(number - 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.exceptions.stackoverflowerror;
|
||||
|
||||
public class RecursionWithCorrectTerminationCondition {
|
||||
public int calculateFactorial(final int number) {
|
||||
return number <= 1 ? 1 : number * calculateFactorial(number - 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.exceptions.stackoverflowerror;
|
||||
|
||||
public class UnintendedInfiniteRecursion {
|
||||
public int calculateFactorial(int number) {
|
||||
return number * calculateFactorial(number - 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.exceptions.throwvsthrows;
|
||||
|
||||
public class DataAccessException extends RuntimeException {
|
||||
|
||||
public DataAccessException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.exceptions.throwvsthrows;
|
||||
|
||||
import com.sun.mail.iap.ConnectionException;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.net.SocketException;
|
||||
|
||||
public class Main {
|
||||
|
||||
public static void main(String[] args) throws FileNotFoundException {
|
||||
TryCatch tryCatch = new TryCatch();
|
||||
|
||||
try {
|
||||
tryCatch.execute();
|
||||
} catch (ConnectionException | SocketException ex) {
|
||||
System.out.println("IOException");
|
||||
} catch (Exception ex) {
|
||||
System.out.println("General exception");
|
||||
}
|
||||
|
||||
checkedException();
|
||||
checkedExceptionWithThrows();
|
||||
}
|
||||
|
||||
private static void checkedExceptionWithThrows() throws FileNotFoundException {
|
||||
File file = new File("not_existing_file.txt");
|
||||
FileInputStream stream = new FileInputStream(file);
|
||||
}
|
||||
|
||||
private static void checkedException() {
|
||||
File file = new File("not_existing_file.txt");
|
||||
try {
|
||||
FileInputStream stream = new FileInputStream(file);
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.exceptions.throwvsthrows;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
public class PersonRepository {
|
||||
|
||||
public List<String> findAll() throws SQLException {
|
||||
throw new SQLException();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.exceptions.throwvsthrows;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class SimpleService {
|
||||
|
||||
private PersonRepository personRepository = new PersonRepository();
|
||||
|
||||
public void wrappingException() {
|
||||
try {
|
||||
personRepository.findAll();
|
||||
} catch (SQLException e) {
|
||||
throw new DataAccessException("SQL Exception", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void runtimeNullPointerException() {
|
||||
String a = null;
|
||||
a.length();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.exceptions.throwvsthrows;
|
||||
|
||||
import com.sun.mail.iap.ConnectionException;
|
||||
|
||||
import java.net.SocketException;
|
||||
|
||||
public class TryCatch {
|
||||
|
||||
public void execute() throws SocketException, ConnectionException, Exception {
|
||||
//code that would throw any of: SocketException, ConnectionException, Exception
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.baeldung.optional;
|
||||
|
||||
public class PersonRepository {
|
||||
|
||||
public String findNameById(String id) {
|
||||
return id == null ? null : "Name";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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("");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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!");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.exceptions.classnotfoundexception;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ClassNotFoundExceptionUnitTest {
|
||||
|
||||
@Test(expected = ClassNotFoundException.class)
|
||||
public void givenNoDriversInClassPath_whenLoadDrivers_thenClassNotFoundException() throws ClassNotFoundException {
|
||||
Class.forName("oracle.jdbc.driver.OracleDriver");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.exceptions.customexception;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class IncorrectFileExtensionExceptionUnitTest {
|
||||
|
||||
@Test
|
||||
public void testWhenCorrectFileExtensionGiven_ReceivesNoException() throws IncorrectFileNameException {
|
||||
assertThat(FileManager.getFirstLine("correctFileNameWithProperExtension.txt")).isEqualTo("Default First Line");
|
||||
}
|
||||
|
||||
@Test(expected = IncorrectFileExtensionException.class)
|
||||
public void testWhenCorrectFileNameExceptionThrown_ReceivesNoException() throws IncorrectFileNameException {
|
||||
StringBuffer sBuffer = new StringBuffer();
|
||||
sBuffer.append("src");
|
||||
sBuffer.append(File.separator);
|
||||
sBuffer.append("test");
|
||||
sBuffer.append(File.separator);
|
||||
sBuffer.append("resources");
|
||||
sBuffer.append(File.separator);
|
||||
sBuffer.append("correctFileNameWithoutProperExtension");
|
||||
FileManager.getFirstLine(sBuffer.toString());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.exceptions.customexception;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class IncorrectFileNameExceptionUnitTest {
|
||||
|
||||
@Test(expected = IncorrectFileNameException.class)
|
||||
public void testWhenIncorrectFileNameExceptionThrown_ReceivesIncorrectFileNameException() throws IncorrectFileNameException {
|
||||
FileManager.getFirstLine("wrongFileName.txt");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWhenCorrectFileNameExceptionThrown_ReceivesNoException() throws IncorrectFileNameException {
|
||||
assertThat(FileManager.getFirstLine("correctFileName.txt")).isEqualTo("Default First Line");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.baeldung.exceptions.exceptionhandling;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.NoSuchFileException;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
public class ExceptionsUnitTest {
|
||||
|
||||
Exceptions exceptions = new Exceptions();
|
||||
|
||||
@Test
|
||||
public void getPlayers() {
|
||||
assertThatThrownBy(() -> exceptions.getPlayers())
|
||||
.isInstanceOf(NoSuchFileException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadAllPlayers() {
|
||||
assertThatThrownBy(() -> exceptions.loadAllPlayers(""))
|
||||
.isInstanceOf(IllegalStateException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getPlayerScoreThrows() {
|
||||
assertThatThrownBy(() -> exceptions.getPlayerScoreThrows(""))
|
||||
.isInstanceOf(FileNotFoundException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getPlayerScoreTryCatch() {
|
||||
assertThatThrownBy(() -> exceptions.getPlayerScoreTryCatch(""))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getPlayerScoreFinally() {
|
||||
assertThatThrownBy(() -> exceptions.getPlayerScoreFinally(""))
|
||||
.isInstanceOf(FileNotFoundException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadAllPlayersThrowingChecked() {
|
||||
assertThatThrownBy(() -> exceptions.loadAllPlayersThrowingChecked(""))
|
||||
.isInstanceOf(TimeoutException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadAllPlayersThrowingUnchecked() {
|
||||
assertThatThrownBy(() -> exceptions.loadAllPlayersThrowingUnchecked(""))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadAllPlayersWrapping() {
|
||||
assertThatThrownBy(() -> exceptions.loadAllPlayersWrapping(""))
|
||||
.isInstanceOf(IOException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadAllPlayersRethrowing() {
|
||||
assertThatThrownBy(() -> exceptions.loadAllPlayersRethrowing(""))
|
||||
.isInstanceOf(PlayerLoadException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadAllPlayersThrowable() {
|
||||
assertThatThrownBy(() -> exceptions.loadAllPlayersThrowable(""))
|
||||
.isInstanceOf(NullPointerException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getPlayerScoreSwallowingExceptionAntiPatternAlternative2() {
|
||||
assertThatThrownBy(() -> exceptions.getPlayerScoreSwallowingExceptionAntiPatternAlternative2(""))
|
||||
.isInstanceOf(PlayerScoreException.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.exceptions.noclassdeffounderror;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class NoClassDefFoundErrorUnitTest {
|
||||
|
||||
@Test(expected = NoClassDefFoundError.class)
|
||||
public void givenInitErrorInClass_whenloadClass_thenNoClassDefFoundError() {
|
||||
NoClassDefFoundErrorExample sample = new NoClassDefFoundErrorExample();
|
||||
sample.getClassWithInitErrors();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.exceptions.sneakythrows;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class SneakyRunnableUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCallSneakyRunnableMethod_thenThrowException() {
|
||||
try {
|
||||
new SneakyRunnable().run();
|
||||
} catch (Exception e) {
|
||||
assertEquals(InterruptedException.class, e.getStackTrace());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.exceptions.sneakythrows;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class SneakyThrowsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCallSneakyMethod_thenThrowSneakyException() {
|
||||
try {
|
||||
SneakyThrows.throwsSneakyIOException();
|
||||
} catch (Exception ex) {
|
||||
assertEquals("sneaky", ex.getMessage().toString());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.exceptions.stackoverflowerror;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class AccountHolderManualTest {
|
||||
@Test(expected = StackOverflowError.class)
|
||||
public void whenInstanciatingAccountHolder_thenThrowsException() {
|
||||
AccountHolder holder = new AccountHolder();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.exceptions.stackoverflowerror;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class CyclicDependancyManualTest {
|
||||
@Test(expected = StackOverflowError.class)
|
||||
public void whenInstanciatingClassOne_thenThrowsException() {
|
||||
ClassOne obj = new ClassOne();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.exceptions.stackoverflowerror;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class InfiniteRecursionWithTerminationConditionManualTest {
|
||||
@Test
|
||||
public void givenPositiveIntNoOne_whenCalcFact_thenCorrectlyCalc() {
|
||||
int numToCalcFactorial = 1;
|
||||
InfiniteRecursionWithTerminationCondition irtc = new InfiniteRecursionWithTerminationCondition();
|
||||
|
||||
assertEquals(1, irtc.calculateFactorial(numToCalcFactorial));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPositiveIntGtOne_whenCalcFact_thenCorrectlyCalc() {
|
||||
int numToCalcFactorial = 5;
|
||||
InfiniteRecursionWithTerminationCondition irtc = new InfiniteRecursionWithTerminationCondition();
|
||||
|
||||
assertEquals(120, irtc.calculateFactorial(numToCalcFactorial));
|
||||
}
|
||||
|
||||
@Test(expected = StackOverflowError.class)
|
||||
public void givenNegativeInt_whenCalcFact_thenThrowsException() {
|
||||
int numToCalcFactorial = -1;
|
||||
InfiniteRecursionWithTerminationCondition irtc = new InfiniteRecursionWithTerminationCondition();
|
||||
|
||||
irtc.calculateFactorial(numToCalcFactorial);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.exceptions.stackoverflowerror;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class RecursionWithCorrectTerminationConditionManualTest {
|
||||
@Test
|
||||
public void givenNegativeInt_whenCalcFact_thenCorrectlyCalc() {
|
||||
int numToCalcFactorial = -1;
|
||||
RecursionWithCorrectTerminationCondition rctc = new RecursionWithCorrectTerminationCondition();
|
||||
|
||||
assertEquals(1, rctc.calculateFactorial(numToCalcFactorial));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.exceptions.stackoverflowerror;
|
||||
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class UnintendedInfiniteRecursionManualTest {
|
||||
@Test(expected = StackOverflowError.class)
|
||||
public void givenPositiveIntNoOne_whenCalFact_thenThrowsException() {
|
||||
int numToCalcFactorial = 1;
|
||||
UnintendedInfiniteRecursion uir = new UnintendedInfiniteRecursion();
|
||||
|
||||
uir.calculateFactorial(numToCalcFactorial);
|
||||
}
|
||||
|
||||
@Test(expected = StackOverflowError.class)
|
||||
public void givenPositiveIntGtOne_whenCalcFact_thenThrowsException() {
|
||||
int numToCalcFactorial = 2;
|
||||
UnintendedInfiniteRecursion uir = new UnintendedInfiniteRecursion();
|
||||
|
||||
uir.calculateFactorial(numToCalcFactorial);
|
||||
}
|
||||
|
||||
@Test(expected = StackOverflowError.class)
|
||||
public void givenNegativeInt_whenCalcFact_thenThrowsException() {
|
||||
int numToCalcFactorial = -1;
|
||||
UnintendedInfiniteRecursion uir = new UnintendedInfiniteRecursion();
|
||||
|
||||
uir.calculateFactorial(numToCalcFactorial);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.exceptions.throwvsthrows;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class SimpleServiceUnitTest {
|
||||
|
||||
SimpleService simpleService = new SimpleService();
|
||||
|
||||
@Test
|
||||
void whenSQLExceptionIsThrown_thenShouldBeRethrownWithWrappedException() {
|
||||
assertThrows(DataAccessException.class,
|
||||
() -> simpleService.wrappingException());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenCalled_thenNullPointerExceptionIsThrown() {
|
||||
assertThrows(NullPointerException.class,
|
||||
() -> simpleService.runtimeNullPointerException());
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user