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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,12 +0,0 @@
package com.baeldung.exceptionhandling;
public class Player {
public int id;
public String name;
public Player(String name) {
this.name = name;
}
}

View File

@@ -1,11 +0,0 @@
package com.baeldung.exceptionhandling;
import java.io.IOException;
public class PlayerLoadException extends Exception {
public PlayerLoadException(IOException io) {
super(io);
}
}

View File

@@ -1,8 +0,0 @@
package com.baeldung.exceptionhandling;
public class PlayerScoreException extends Exception {
public PlayerScoreException(Exception e) {
super(e);
}
}

View File

@@ -1,8 +0,0 @@
package com.baeldung.exceptionhandling;
public class TimeoutException extends Exception {
public TimeoutException(String message) {
super(message);
}
}

View File

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

View File

@@ -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
}*/
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,8 +0,0 @@
package com.baeldung.stackoverflowerror;
public class AccountHolder {
private String firstName;
private String lastName;
AccountHolder jointAccountHolder = new AccountHolder();
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,7 +0,0 @@
package com.baeldung.stackoverflowerror;
public class UnintendedInfiniteRecursion {
public int calculateFactorial(int number) {
return number * calculateFactorial(number - 1);
}
}

View File

@@ -1,9 +0,0 @@
package com.baeldung.throwsexception;
public class DataAccessException extends RuntimeException {
public DataAccessException(String message, Throwable cause) {
super(message, cause);
}
}

View File

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

View File

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

View File

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

View File

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