我知道异常是在运行时发生的,而不是在编译时发生的。
因此,此代码无需任何编译时间即可成功编译,java.lang.ArithmeticException: / by zero
但类型为Exception,但仅在运行时给出异常
class divzero{
public static void main(String[] arg){
System.out.print(3/0);
}
}
但是当我使用BufferedReader
类unreported exception java.io.IOException; must be caught or declared to be thrown
时,在编译下面给出的代码时会说“ ”。我认为它应该在运行时而不是在编译时产生此异常,因为异常是在编译时发生的。
import java.io.*;
class Bufferedreaderclass{
public static void main(String[] arg)
{
System.out.print("mazic of buffer reader \n Input : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input;
input = br.readLine();
System.out.print("Your input is: "+input);
}
}
我知道,我应该抛出IOException
类型异常,但是为什么呢?我想知道为什么unreported exception java.io.IOException
在编译时而不是在运行时。
请向我清楚说明为什么它会这样?
由于IOException
是一个已检查的异常,因此必须使用try...catch
或'throw'。
try...catch
块的用法如下。它将处理的运行时发生IOException
。
import java.io.*;
class Bufferedreaderclass{
public static void main(String[] arg)
{
System.out.print("mazic of buffer reader \n Input : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = "";
try{
input = br.readLine();
System.out.print("Your input is: "+input);
} catch (IOException e) {
// do something useful with this exception
}
}
有关使用的更多信息try...catch
,请参见https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句