我知道如何创建对具有String参数并返回一个方法的方法的引用int,它是:
Function<String, Integer>
Run Code Online (Sandbox Code Playgroud)
但是,如果函数抛出异常,这不起作用,比如说定义为:
Integer myMethod(String s) throws IOException
Run Code Online (Sandbox Code Playgroud)
我该如何定义这个参考?
在本网站上为另一个答案编写代码时,我遇到了这样的特点:
static void testSneaky() {
final Exception e = new Exception();
sneakyThrow(e); //no problems here
nonSneakyThrow(e); //ERRROR: Unhandled exception: java.lang.Exception
}
@SuppressWarnings("unchecked")
static <T extends Throwable> void sneakyThrow(Throwable t) throws T {
throw (T) t;
}
static <T extends Throwable> void nonSneakyThrow(T t) throws T {
throw t;
}
Run Code Online (Sandbox Code Playgroud)
首先,我很困惑为什么sneakyThrow对编译器调用是好的.T在没有提到未经检查的异常类型的任何地方时,它推断出什么可能的类型?
其次,接受这是有效的,为什么编译器会在nonSneakyThrow电话中抱怨?它们看起来非常相像.
在Java 8中使用FP习惯用法时,异常(尤其是已检查的异常)会严重中断程序逻辑的流程.以下是一个任意示例:
String s1 = "oeu", s2 = "2";
Stream.of(s1, s2).forEach(s ->
System.out.println(Optional.of(s).map(Integer::parseInt).get()));
Run Code Online (Sandbox Code Playgroud)
当不可解析的字符串出现异常时,上面的代码会中断.但是说我只想用默认值替换它,就像我可以用Optional:
Stream.of(s1, s2).forEach(s ->
System.out.println(Optional.of(s)
.map(Integer::parseInt)
.orElse(-1)));
Run Code Online (Sandbox Code Playgroud)
当然,这仍然失败因为Optional只处理nulls.我想要的东西如下:
Stream.of(s1, s2).forEach(s ->
System.out.println(
Exceptional.of(s)
.map(Integer::parseInt)
.handle(NumberFormatException.class, swallow())
.orElse(-1)));
Run Code Online (Sandbox Code Playgroud)
注意:这是一个自我回答的问题.
所以我试图重构以下代码:
/**
* Returns the duration from the config file.
*
* @return The duration.
*/
private Duration durationFromConfig() {
try {
return durationFromConfigInner();
} catch (IOException ex) {
throw new IllegalStateException("The config file (\"" + configFile + "\") has not been found.");
}
}
/**
* Returns the duration from the config file.
*
* Searches the log file for the first line indicating the config entry for this instance.
*
* @return The duration.
* @throws FileNotFoundException If …Run Code Online (Sandbox Code Playgroud) 来自java.lang.Exception类javaDocs :
如果方法或构造函数的throws子句可以通过执行方法或构造函数抛出并在方法或构造函数边界外传播,则需要在方法或构造函数的throws子句中声明已检查的异常.
但请考虑以下代码:
package other;
public class CheckedExceptionHandling {
private static <E extends Exception> void throwException() throws E {
throw (E) new CheckedException2(); // unchecked cast warning
}
private static void setUncaughtExceptionHandler() {
Thread.currentThread().setUncaughtExceptionHandler((t, e) -> {
System.out.println("Unhandled exception: " + e.getClass()); // reports CheckedExceptionHandling$CheckedException2
});
}
public static void main(String[] args) /* no checked exceptions declared! */ {
setUncaughtExceptionHandler();
try {
CheckedExceptionHandling.<CheckedException1>throwException();
} catch (CheckedException1 e) {
System.out.println(e); // never gets here
}
}
// checked …Run Code Online (Sandbox Code Playgroud) 我正在阅读有关Java中已检查和未检查的异常的文章,并找到此文章/链接:https : //projectlombok.org/disableCheckedExceptions.html
根据这篇文章,这只是为javac开发的一种hack。
考虑下面的代码片段:
import java.io.*;
class Example
{
public static void main(String args[]) throws IOException
{
FileInputStream fis = null;
fis = new FileInputStream("myfile.txt");
int k;
while(( k = fis.read() ) != -1)
{
System.out.print((char)k);
}
fis.close();
}
}
Run Code Online (Sandbox Code Playgroud)
在这里我必须写, public static void main(String args[]) throws IOException
因为我正在尝试打开文件。在这里,“ throws”子句是必须的。没有它,我会得到一个错误。如果我确定要打开的文件的存在怎么办。提到的位置中的iemyfile.txt。在某些时候,您可能会觉得代码不需要检查异常。
Java是否提供了根据需要禁用检查异常的功能?
即使做了很多研究,我也找不到合适的答案。