Если уж очень хочется то в 8ой Жаве можно попытаться извратиться.
Вот только похоже придется делать много Try*<T> для методов с конкретным набором аргументов.
public class TryCatch
{
@FunctionalInterface
public interface Try<T>
{
T trai() throws Exception;
}
@FunctionalInterface
public interface TryDouble<T>
{
T trai(Double d) throws Exception;
}
@FunctionalInterface
public interface Catch<T>
{
T katch(Exception e);
}
public static <T> T trai(TryDouble<T> call, Double d)
{
return trai(call, TryCatch::katch, d);
}
public static <T> T trai(TryDouble<T> call, Catch<T> katch, Double d)
{
try
{
return call.trai(d);
}
catch (Exception e)
{
return katch.katch(e);
}
}
public static <T> T trai(Try<T> call)
{
return trai(call, TryCatch::katch);
}
public static <T> T trai(Try<T> call, Catch<T> katch)
{
try
{
return call.trai();
}
catch (Exception e)
{
return katch.katch(e);
}
}
public static <T> T katch(Exception exception)
{
exception.printStackTrace();
return null;
}
}
public class Main
{
public static void main(String[] args)
{
Integer i = TryCatch.trai(Main::meth1);
Double d = TryCatch.trai(Main::meth2);
System.out.println(i);
System.out.println(d);
Double d1 = TryCatch.trai(Main::meth2, (e) -> 2.0);
Double d2 = TryCatch.trai(Main::meth2, Main::myKatch);
Double d3 = TryCatch.trai(Main::meth2, (e) ->
{
e.printStackTrace();
return null;
});
System.out.println(d1);
System.out.println(d2);
System.out.println(d3);
Double d4 = TryCatch.trai(Main::meth3, 1.0);
System.out.println(d4);
Double d5 = TryCatch.trai(Main::meth2, (e) ->
{
throw new RuntimeException(e);
});
System.out.println(d5);
}
public static Integer meth1() throws Exception
{
return 10;
}
public static Double meth2() throws Exception
{
throw new Exception();
}
public static Double meth3(Double d) throws Exception
{
return d;
}
public static <T> T myKatch(Exception exception)
{
System.out.println("My Catch!");
return null;
}
}