我已经在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中的异常checked和unchecked异常方面遇到了一些问题.
checked异常应该在编译期间寻找异常.在不同来源中提供的示例引用数据库连接,文件处理作为其中一些,而unchecked异常应该在程序员的部分寻找错误,例如超出数组范围的索引等.不应该反过来吗?我的意思是,数据库连接是在运行时完成的,对吧?文件处理也是如此.在编译期间没有打开文件句柄,为什么在编译期间会查找可能的错误?另一方面,在程序中已完成索引超出其范围的数组,可在编译期间检查(如果用户在运行时提供异常索引,则可以将其作为运行时)问题).我在这里错过了什么?
2其次,如何才能RunTimeException,本身是unchecked,子类Exception,这是checked?这意味着什么?
我在Herbert Schildt的书中找到了一个例子来解释checked异常的用法:
class ThrowsDemo {
public static char prompt(String str)
throws java.io.IOException {
System.out.print(str + ": ");
return (char) System.in.read();
}
public static void main(String args[]) {
char ch;
try {
ch = prompt("Enter a letter");
}
catch(java.io.IOException exc) {
System.out.println("I/O exception occurred.");
ch = 'X';
}
System.out.println("You pressed " + ch);
}
}
Run Code Online (Sandbox Code Playgroud)
这throws条款是否必要?为什么我不能正常做这样的try-catch …
我们知道如果发生任何错误或任何未经检查的异常,那么我们的程序将停止,那么它们之间有什么区别?
class MyException extends Exception {
MyException() {}
MyException(String msg) { super(msg);}
}
public class NewException {
static void f() throws MyException {
System.out.println("throwing exception from f()");
throw new ClassCastException();
}
static void g() throws MyException {
System.out.println("throwing exception from g()");
throw new MyException("parametrized ");
}
public static void main(String ...strings ) {
try {
f();
}
catch(MyException e) {
e.printStackTrace(System.out);
}
try {
g();
}
catch(MyException e) {
e.printStackTrace(System.out);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在函数f()中,我指定将抛出"MyException"异常,实际上我抛出了一些与MyException无关的其他异常,但编译器仍然没有抱怨.为什么?