Merge branch 'readme-30' of https://github.com/sjmillington/tutorials into readme-30
This commit is contained in:
@@ -4,30 +4,22 @@ This module contains articles about core features in the Java language
|
||||
|
||||
### 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)
|
||||
@@ -38,4 +30,5 @@ This module contains articles about core features in the Java language
|
||||
- [Attaching Values to Java Enum](https://www.baeldung.com/java-enum-values)
|
||||
- [Variable Scope in Java](https://www.baeldung.com/java-variable-scope)
|
||||
- [Java Classes and Objects](https://www.baeldung.com/java-classes-objects)
|
||||
- [[More --> ]](/core-java-modules/core-java-lang-2)
|
||||
- [A Guide to Java Enums](https://www.baeldung.com/a-guide-to-java-enums)
|
||||
- [[More --> ]](/core-java-modules/core-java-lang-2)
|
||||
@@ -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>
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
package com.baeldung.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;
|
||||
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package com.baeldung.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;
|
||||
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.baeldung.chainedexception.exceptions;
|
||||
|
||||
public class GirlFriendOfManagerUpsetException extends Exception {
|
||||
|
||||
public GirlFriendOfManagerUpsetException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public GirlFriendOfManagerUpsetException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.baeldung.chainedexception.exceptions;
|
||||
|
||||
public class ManagerUpsetException extends Exception {
|
||||
|
||||
public ManagerUpsetException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public ManagerUpsetException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.baeldung.chainedexception.exceptions;
|
||||
|
||||
public class NoLeaveGrantedException extends Exception {
|
||||
|
||||
public NoLeaveGrantedException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public NoLeaveGrantedException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.baeldung.chainedexception.exceptions;
|
||||
|
||||
public class TeamLeadUpsetException extends Exception {
|
||||
|
||||
public TeamLeadUpsetException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public TeamLeadUpsetException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package com.baeldung.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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.baeldung.customexception;
|
||||
|
||||
public class IncorrectFileExtensionException extends RuntimeException{
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public IncorrectFileExtensionException(String errorMessage, Throwable err) {
|
||||
super(errorMessage, err);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.baeldung.customexception;
|
||||
|
||||
public class IncorrectFileNameException extends Exception {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public IncorrectFileNameException(String errorMessage, Throwable err) {
|
||||
super(errorMessage, err);
|
||||
}
|
||||
}
|
||||
@@ -1,212 +0,0 @@
|
||||
package com.baeldung.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;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.baeldung.exceptionhandling;
|
||||
|
||||
public class MyException extends Throwable {
|
||||
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.baeldung.exceptionhandling;
|
||||
|
||||
public class Player {
|
||||
|
||||
public int id;
|
||||
public String name;
|
||||
|
||||
public Player(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package com.baeldung.exceptionhandling;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class PlayerLoadException extends Exception {
|
||||
|
||||
public PlayerLoadException(IOException io) {
|
||||
super(io);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.baeldung.exceptionhandling;
|
||||
|
||||
public class PlayerScoreException extends Exception {
|
||||
|
||||
public PlayerScoreException(Exception e) {
|
||||
super(e);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.baeldung.exceptionhandling;
|
||||
|
||||
public class TimeoutException extends Exception {
|
||||
|
||||
public TimeoutException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.baeldung.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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.keywords.finalkeyword;
|
||||
|
||||
public final class Child extends Parent {
|
||||
|
||||
@Override
|
||||
void method1(int arg1, final int arg2) {
|
||||
// OK
|
||||
}
|
||||
|
||||
/* @Override
|
||||
void method2() {
|
||||
// Compilation error
|
||||
}*/
|
||||
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.baeldung.keywords.finalkeyword;
|
||||
|
||||
/*public class GrandChild extends Child {
|
||||
// Compilation error
|
||||
}*/
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.baeldung.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
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.baeldung.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");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.baeldung.noclassdeffounderror;
|
||||
|
||||
public class ClassWithInitErrors {
|
||||
static int data = 1 / 0;
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package com.baeldung.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;
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.baeldung.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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package com.baeldung.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();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.baeldung.stackoverflowerror;
|
||||
|
||||
public class AccountHolder {
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
AccountHolder jointAccountHolder = new AccountHolder();
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.baeldung.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;
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.baeldung.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;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package com.baeldung.stackoverflowerror;
|
||||
|
||||
public class InfiniteRecursionWithTerminationCondition {
|
||||
public int calculateFactorial(final int number) {
|
||||
return number == 1 ? 1 : number * calculateFactorial(number - 1);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package com.baeldung.stackoverflowerror;
|
||||
|
||||
public class RecursionWithCorrectTerminationCondition {
|
||||
public int calculateFactorial(final int number) {
|
||||
return number <= 1 ? 1 : number * calculateFactorial(number - 1);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package com.baeldung.stackoverflowerror;
|
||||
|
||||
public class UnintendedInfiniteRecursion {
|
||||
public int calculateFactorial(int number) {
|
||||
return number * calculateFactorial(number - 1);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.baeldung.throwsexception;
|
||||
|
||||
public class DataAccessException extends RuntimeException {
|
||||
|
||||
public DataAccessException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package com.baeldung.throwsexception;
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.baeldung.throwsexception;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
public class PersonRepository {
|
||||
|
||||
public List<String> findAll() throws SQLException {
|
||||
throw new SQLException();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package com.baeldung.throwsexception;
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.baeldung.throwsexception;
|
||||
|
||||
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,11 +0,0 @@
|
||||
package com.baeldung.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");
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.baeldung.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());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package com.baeldung.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");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
package com.baeldung.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);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.baeldung.noclassdeffounderror;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class NoClassDefFoundErrorUnitTest {
|
||||
|
||||
@Test(expected = NoClassDefFoundError.class)
|
||||
public void givenInitErrorInClass_whenloadClass_thenNoClassDefFoundError() {
|
||||
NoClassDefFoundErrorExample sample = new NoClassDefFoundErrorExample();
|
||||
sample.getClassWithInitErrors();
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.baeldung.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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.baeldung.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());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.baeldung.stackoverflowerror;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class AccountHolderManualTest {
|
||||
@Test(expected = StackOverflowError.class)
|
||||
public void whenInstanciatingAccountHolder_thenThrowsException() {
|
||||
AccountHolder holder = new AccountHolder();
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.baeldung.stackoverflowerror;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class CyclicDependancyManualTest {
|
||||
@Test(expected = StackOverflowError.class)
|
||||
public void whenInstanciatingClassOne_thenThrowsException() {
|
||||
ClassOne obj = new ClassOne();
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package com.baeldung.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);
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.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));
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package com.baeldung.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);
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package com.baeldung.throwsexception;
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user