【发布时间】:2013-07-04 16:10:39
【问题描述】:
我是Java初学者,知道try...catch语句是用来处理异常的;表示当try 块抛出异常时,将执行catch 块。所以,我的问题是,当我尝试以下代码(没有try catch)时,它会在read() 方法中抛出一个未报告的IOException,但是当我使用try catch 时它工作正常。
为什么在try 块中发生上述异常并打印exception occured 时,控件不转移到catch 语句?
这是我的代码:
class Test00 {
public static void main(String args[]) {
char ch;
try {
ch=(char)System.in.read();//here exception is thrown without using try..catch
System.out.println(ch);
} catch(Exception e) {
System.out.print("exception occured");
}
}
}
我认为编译器说要抛出异常,这就是代码使用 try catch 工作的原因。但为什么不执行 catch 块?我是不是搞错了。
【问题讨论】:
-
未报告是什么意思??
-
可能是该输入从未引发异常!
-
你是说在运行程序时抛出了异常,还是说编译器在尝试编译程序时抱怨没有捕获到异常??
-
(提示:报告 SO 上的问题时,总是复制/粘贴您收到的 exact 错误消息。并且在报告 Java 异常时确保至少还包括堆栈跟踪的前 10 行左右。)
标签: java exception exception-handling