我已经在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
如何从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的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) 假设我有一个类和一个方法
class A {
void foo() throws Exception() {
...
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想为A一个流传递的每个实例调用foo,如:
void bar() throws Exception {
Stream<A> as = ...
as.forEach(a -> a.foo());
}
Run Code Online (Sandbox Code Playgroud)
问题:如何正确处理异常?代码无法在我的机器上编译,因为我没有处理foo()可能抛出的异常.在throws Exception的bar似乎是没用在这里.这是为什么?