我已经在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
在下面的源代码我重新抛出一个Exception.
为什么没有必要将throws关键字放在方法的签名上?
public void throwsOrNotThrowsThatsTheQuestion() {
try {
// Any processing
} catch (Exception e) {
throw e;
}
}
Run Code Online (Sandbox Code Playgroud) 今天我在Java中遇到了一个奇怪的场景.我在我的方法中有一个try..catch块,它没有任何throws子句,我能够抛出catch块中捕获的异常对象.它是Exception类的对象,因此它不是未经检查的异常.此外,如果出现异常,它不会打印堆栈跟踪,而是异常被吞没.
下面是我的代码示例,
public class ExceptionTest {
public void test() {
try
{
// Some code which may throw exception.
}
catch(Exception ex)
{
// Compiler should ask me to have a *throws Exception* in the signature, when I am throwing an exception object.
throw ex;
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我抛出一个新的异常对象而不是捕获的异常对象,编译器会要求我在方法签名中有一个throws子句.
注意:在Java 7或8中运行时,我遇到了这种情况.
我想知道,抛出的物体在哪里?有任何想法的人请...