Java跳过尝试捕获以抛出功能 [英] Java skip try catch for throwable fuction

查看:83
本文介绍了Java跳过尝试捕获以抛出功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道Java中是否有一种方法可以跳过我认为不会抛出异常的可抛出函数的try-catch方法。

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拥有这段代码:

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


错误:(97,30)错误:未报告的异常ParseException;必须被捕获或声明为被抛出

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

我可以通过放置 format.parse来消除此错误()在try-catch中。

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

在Swift 2错误处理中,有一个选项可以进行 try! someFunction()将编译并执行throwable函数,如果发生错误则崩溃。

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.

在Java中是否有类似的方法,所以我

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?

推荐答案

不是真的要把所有我知道不会在任何地方的异常都放入try-catch中的小任务吗? ,但是您可以编写一个辅助方法来欺骗编译器,使他们认为未检查的异常是未检查的。例如:

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;
}

您将像这样使用它:

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

您还可以将已检查的异常包装为未检查的异常,例如jOOL所做的此处

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

这篇关于Java跳过尝试捕获以抛出功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆