Skip to content

Instantly share code, notes, and snippets.

View benweidig's full-sized avatar

Ben Weidig benweidig

View GitHub Profile
protected Throwable(String message,
Throwable cause,
boolean enableSuppression,
boolean writableStackTrace) {
if (writableStackTrace) {
fillInStackTrace();
}
else {
stackTrace = null;
public float divide(float divident, float divisor) {
try {
return divident / divisor
}
catch (ArithmeticException e) {
System.out.println("Division error");
}
return 0.0f;
}
public void doWork(List<MyBean> beans) {
beans.stream()
.map(this::mapToItem)
.forEach(this::workOnItem);
}
private MyItem mapToItem(MyBean bean) {
try {
MyItem item = ...;
return item;
@FunctionalInterface
interface ExFunction<T, R, E extends Exception> {
R apply(T t) throws E;
}
<T, R, E extends Exception> Function<T, R> uncheck(ExFunction<T, R, E> fn) {
return arg -> {
try {
return fn.apply(arg);
void doWork(List<MyBean> beans) throws ValidationException, IOException {
beans.stream()
.map(bean -> ...)
.forEach(item -> ...);
}
void doWork(List<MyBean> beans) {
beans.stream()
.map(bean -> {
try {
// do some work that might throw
}
catch (ValidationException e) {
// handle appropriately
}
})
class CustomerRegistrationException extends Exception {
private final String email;
public CustomerRegistrationException(String email) {
super("Registration failed for " + email);
this.email = email;
}
public String getEmail() {
public class ValidationException extends Exception {
private final String field;
public ValidationException(String field,
String message,
Throwable cause) {
super(message, cause);
this.field = field;
}
try {
...
}
catch (IOException e) {
throw new MyCustomException("More information", e);
}
interface WithException {
void doWork() throws IOException;
}
class WithoutException implements WithException {
// We omit the exception in the implementation
@Override
public void doWork() {