我已经在StackOverFlow上阅读了有关已检查和未经检查的异常的多个帖子.老实说,我还是不太确定如何正确使用它们.
Joshua Bloch在" Effective Java "中说过
对可恢复条件使用已检查的异常,对编程错误使用运行时异常(第2版中的第58项)
让我们看看我是否正确理解这一点.
以下是我对已检查异常的理解:
try{
String userInput = //read in user input
Long id = Long.parseLong(userInput);
}catch(NumberFormatException e){
id = 0; //recover the situation by setting the id to 0
}
Run Code Online (Sandbox Code Playgroud)
1.以上是否考虑了检查异常?
2. RuntimeException是未经检查的异常吗?
以下是我对未经检查的异常的理解:
try{
File file = new File("my/file/path");
FileInputStream fis = new FileInputStream(file);
}catch(FileNotFoundException e){
//3. What should I do here?
//Should I "throw new FileNotFoundException("File not found");"?
//Should I log?
//Or should I System.exit(0);?
}
Run Code Online (Sandbox Code Playgroud)
4.现在,上述代码也不能成为检查异常吗?我可以尝试恢复这样的情况吗?我可以吗?(注意:我的第3个问题在catch上面)
try{
String …Run Code Online (Sandbox Code Playgroud) java exception runtimeexception checked-exceptions unchecked-exception
我知道如何创建对具有String参数并返回一个方法的方法的引用int,它是:
Function<String, Integer>
Run Code Online (Sandbox Code Playgroud)
但是,如果函数抛出异常,这不起作用,比如说定义为:
Integer myMethod(String s) throws IOException
Run Code Online (Sandbox Code Playgroud)
我该如何定义这个参考?
如何从Java 8流/ lambdas中抛出CHECKED异常?
换句话说,我想像这样编译代码:
public List<Class> getClasses() throws ClassNotFoundException {
List<Class> classes =
Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
.map(className -> Class.forName(className))
.collect(Collectors.toList());
return classes;
}
Run Code Online (Sandbox Code Playgroud)
此代码无法编译,因为Class.forName()上面的方法抛出ClassNotFoundException,检查.
请注意我不希望将已检查的异常包装在运行时异常中,而是抛出包装的未经检查的异常.我想抛出已检查的异常本身,而不是向流添加丑陋的try/ catches.
在Java 8中,我们有Stream <T>类,它奇怪地有一个方法
Iterator<T> iterator()
Run Code Online (Sandbox Code Playgroud)
所以你会期望它实现接口Iterable <T>,这需要完全这个方法,但事实并非如此.
当我想使用foreach循环遍历Stream时,我必须做类似的事情
public static Iterable<T> getIterable(Stream<T> s) {
return new Iterable<T> {
@Override
public Iterator<T> iterator() {
return s.iterator();
}
};
}
for (T element : getIterable(s)) { ... }
Run Code Online (Sandbox Code Playgroud)
我在这里错过了什么吗?
如何以递归方式列出Java中目录下的所有文件?框架是否提供任何实用程序?
我看到很多hacky实现.但没有来自框架或nio
我在尝试Java 8的Lambda表达式时遇到了问题.通常它工作正常,但现在我有方法可以抛出IOException.最好看一下以下代码:
class Bank{
....
public Set<String> getActiveAccountNumbers() throws IOException {
Stream<Account> s = accounts.values().stream();
s = s.filter(a -> a.isActive());
Stream<String> ss = s.map(a -> a.getNumber());
return ss.collect(Collectors.toSet());
}
....
}
interface Account{
....
boolean isActive() throws IOException;
String getNumber() throws IOException;
....
}
Run Code Online (Sandbox Code Playgroud)
问题是,它不能编译,因为我必须捕获isActive-和getNumber-Methods的可能例外.但即使我明确使用如下所示的try-catch-Block,它仍然无法编译,因为我没有捕获异常.所以要么JDK中存在错误,要么我不知道如何捕获这些异常.
class Bank{
....
//Doesn't compile either
public Set<String> getActiveAccountNumbers() throws IOException {
try{
Stream<Account> s = accounts.values().stream();
s = s.filter(a -> a.isActive());
Stream<String> ss = s.map(a -> a.getNumber());
return ss.collect(Collectors.toSet());
}catch(IOException ex){
} …Run Code Online (Sandbox Code Playgroud) 假设我有一个抛出运行时异常的方法.我正在使用a Stream来对列表中的项目调用此方法.
class ABC {
public void doStuff(MyObject myObj) {
if (...) {
throw new IllegalStateException("Fire! Fear! Foes! Awake!");
}
// do stuff...
}
public void doStuffOnList(List<MyObject> myObjs) {
try {
myObjs.stream().forEach(ABC:doStuff);
} catch(AggregateRuntimeException??? are) {
...
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在我希望处理列表中的所有项目,并将各个项目的任何运行时异常收集到最终将抛出的"聚合"运行时异常中.
在我的真实代码中,我正在进行第三方API调用,这可能会引发运行时异常.我想确保处理所有项目并在最后报告任何错误.
我可以想出一些方法来解决这个问题,例如map()捕获并返回异常的函数(..shudder ..).但有没有一种本地方式来做到这一点?如果没有,还有另一种方法可以干净利落地实施吗?
我有以下目录结构:
/path/to/stuff/org/foo/bar/
/path/to/stuff/org/foo/bar/1.2.3/
/path/to/stuff/org/foo/bar/1.2.3/myfile.ext
/path/to/stuff/org/foo/bar/1.2.4/
/path/to/stuff/org/foo/bar/1.2.4/myfile.ext
/path/to/stuff/org/foo/bar/blah/
/path/to/stuff/org/foo/bar/blah/2.1/
/path/to/stuff/org/foo/bar/blah/2.1/myfile.ext
/path/to/stuff/org/foo/bar/blah/2.2/
/path/to/stuff/org/foo/bar/blah/2.2/myfile.ext
Run Code Online (Sandbox Code Playgroud)
我想得到以下输出:
/path/to/stuff/org/foo/bar/
/path/to/stuff/org/foo/bar/blah/
Run Code Online (Sandbox Code Playgroud)
我有以下代码(下面),这是低效的,因为它打印出来:
/path/to/stuff/org/foo/bar/
/path/to/stuff/org/foo/bar/
/path/to/stuff/org/foo/bar/blah/
/path/to/stuff/org/foo/bar/blah/
Run Code Online (Sandbox Code Playgroud)
这是Java代码:
public class LocatorTest
{
@Test
public void testLocateDirectories()
throws IOException
{
long startTime = System.currentTimeMillis();
Files.walk(Paths.get("/path/to/stuff/"))
.filter(Files::isDirectory)
.forEach(Foo::printIfArtifactVersionDirectory);
long endTime = System.currentTimeMillis();
System.out.println("Executed in " + (endTime - startTime) + " ms.");
}
static class Foo
{
static void printIfArtifactVersionDirectory(Path path)
{
File f = path.toAbsolutePath().toFile();
List<String> filePaths = Arrays.asList(f.list(new MyExtFilenameFilter()));
if (!filePaths.isEmpty())
{
System.out.println(path.getParent());
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
过滤器: …
我正在尝试使用 Java Streams 写入文件。据我所知,只要将异常抛出,就不必捕获异常。然而编译器会抛出一个错误(在stream.foreach()...的行上)并说
错误:未报告的异常 IOException;必须被抓住或宣布被扔出
有人可以解释这是为什么吗?(我只对使用流的解决方案感兴趣)
public void save(String file, ArrayList<String> text) throws IOException {
FileWriter fw = new FileWriter(file);
text.stream().forEach(x->fw.write(x +"\n"));
fw.close();
}
Run Code Online (Sandbox Code Playgroud)
Netbeans 建议这样做,但是有没有更短的方法呢?
public void save(String file, ArrayList<String> text) throws IOException {
FileWriter fw = new FileWriter(file);
text.stream().forEach(x->{
try {
fw.write(x +"\n");
} catch (IOException ex) {
...
}
});
fw.close();
}
Run Code Online (Sandbox Code Playgroud) Java Stream.forEach函数有一个严重的限制,即它的消费者不可能抛出已检查的异常.因此,我想逐个访问Stream的元素.
我想做这样的事情:
while(true) {
Optional<String> optNewString = myStream.findAny();
if (optNewString.isPresent())
doStuff(optNewString.get());
else
break;
}
Run Code Online (Sandbox Code Playgroud)
但是,findAny是一种短路终端操作.也就是说,它会关闭流.此代码将在while循环的第二次迭代时崩溃.我不能简单地将所有元素放在一个数组中,并逐个遍历该数组,因为可能存在数千万个元素.
请注意我不会问如何从内部抛出异常forEach.这个问题已经得到解答.
我正在使用Java 8 Files.walk(..)来计算.mp3文件夹中包含的文件以及其中的所有文件夹。换句话说,我正在访问文件树的所有级别。
当我得到java.nio.file.AccessDeniedException的Stream关闭,我不希望这种行为。我需要它来忽略或打印异常并继续计算文件。下面是我使用的代码:):
/**
* Count files in a directory (including files in all sub
* directories)
*
* @param directory
* the directory to start in
* @return the total number of files
*/
public int countFiles(File dir) {
if (dir.exists())
try (Stream<Path> paths = Files.walk(Paths.get(dir.getPath()), FileVisitOption.FOLLOW_LINKS)) {
return (int) paths.filter(path -> {
// i am using something different here but i changed
// it just for the purpose of …Run Code Online (Sandbox Code Playgroud) 我有一个方法,我遍历List并创建List.在这样做时,我调用一个方法(createResult)来给一个Result也抛出CustomException,我将它包装为ResultClassException.但我一直收到一个错误,指出未处理的异常.
我的代码:
private List<Result> getResultList(List<String> results) throws ResultClassException {
List<Result> resultList = new ArrayList<>();
results.forEach(
(resultName) -> {
if (!resultRepository.contains(resultName)) {
try {
final Result result = createResult(resultName);
resultList.add(result);
} catch (CustomException e) {
throw new ResultClassException("Error",e);
}
} else {
resultList.add(resultRepository.get(resultName));
log.info("Result {} already exists.", resultName);
}
}
);
return Collections.unmodifiableList(resultList);
}
Run Code Online (Sandbox Code Playgroud)
有人能说出我做错了什么吗?