Java skip try catch for throwable fuction

梦想的初衷 提交于 2020-01-17 05:38:14

问题


I wonder if there is a way in Java to 'skip' the try-catch method for a throwable function that I know will not throw an exception.

I have this piece of code:

DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date = format.parse(dateString); // <-- Compiler error here
Log.i(PF.TAG, date.toString());

I get compiler error saying an exception is not handled

Error:(97, 30) error: unreported exception ParseException; must be caught or declared to be thrown

I can get rid of this error by putting the format.parse() inside a try-catch.

In Swift 2 error handling there is an option to do try! someFunction() which will compile and execute the throwable function and crash if there is an error.

Is there a similar way in Java so I dont have to put all the small tasks which I know will not throw an exception in a try-catch everywhere?


回答1:


Not really, but you can write a helper method to trick the compiler into believing that the checked exception is unchecked. For example:

public static <T> T uncheck(Callable<T> callable) {
  try {
    return callable.call();
  } catch (Throwable t) {
    return rethrow(t);
  }
}

@SuppressWarnings("unchecked")
private static <E extends Throwable, T> T rethrow(Throwable t) throws E {
  throw (E) t;
}

And you would use it like this:

Date date = uncheck(() -> format.parse(dateString));

You could also wrap the checked exception into an unchecked exception, like what jOOL does here.




回答2:


Not really.

In Java there are generally two types of exceptions - checked (extend Exception) or unchecked (extend RuntimeException).

Handling the checked exceptions in some way is mandatory and not doing so causes a compile - time exception, like in your case. There are two ways of handling them:

  • Try - catch blocks. If you want, you can just ignore by providing an empty catch clause and a useful comment, specifying why this should never happen.
    • the throws declaration. It is a part of the method declaration and shifts the responsibility of dealing with the exception to the client of the declared method.

If you want to emulate the Swift construct you mentioned, what you need is something like this:

try {
    someFunction()
} catch (Exception e) {
    throw new <some runtime exception>
}

In this way you "swallow" the checked exception, stopping it's propagation and, instead, throwing a non - checked runtime exception, that doesn't force callers to handle it and will cause a crash if the original exception occurs.




回答3:


You can't avoid dealing with that exception at some point because it's checked, but you can avoid the need for lots of try-catch constructs if you refactor the call into a separate method that handles the exception:

public class DateUtils {

    private DateUtils() { throw new AssertionError(); }

    public static Date parse(String toParse, DateFormat format) {
        try {
            return format.parse(toParse);
        catch (ParseException e) {
            // Exception handling code here. Maybe you want to log the error
            // somewhere? Then either re-throw as a RuntimeException or return some
            // default value.
        }
    }
}

Then you'd do:

DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date = DateUtils.parse(dateString, format);
Log.i(PF.TAG, date.toString());


来源:https://stackoverflow.com/questions/33937250/java-skip-try-catch-for-throwable-fuction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!