简体   繁体   中英

Java skip try catch for throwable fuction

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() 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?

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 .

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM