Skip to content

Instantly share code, notes, and snippets.

@tmanOC
Created September 16, 2019 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmanOC/da327617c8d0db834276fd5ad8b2773d to your computer and use it in GitHub Desktop.
Save tmanOC/da327617c8d0db834276fd5ad8b2773d to your computer and use it in GitHub Desktop.
import java.util.Optional;
public class ExceptionUtil {
public interface MayThrow<R>{
public R method() throws Exception;
}
public static <T> T tryBlock(MayThrow<T> throwing) {
try{
T obj = throwing.method();
return obj;
} catch(Exception e) {
System.out.println(e.getLocalizedMessage());
return null;
}
}
public static <T> Optional<T> tryBlockOptional(MayThrow<T> throwing) {
try{
return Optional.ofNullable(throwing.method());
} catch(Exception e) {
return Optional.empty();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment