为什么BufferedReader类在编译时而不是在运行时产生异常

г1ји

我知道异常是在运行时发生的,而不是在编译时发生的。

因此,此代码无需任何编译时间即可成功编译,java.lang.ArithmeticException: / by zero类型Exception,但仅在运行时给出异常

class divzero{
public static void main(String[] arg){
System.out.print(3/0);
}
}

但是当我使用BufferedReaderunreported 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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

为什么在运行时而不是在编译时评估使用constexpr初始化变量

如何使用GHC.TypeLits.TypeError在编译时而不是在运行时获取类型错误?

为什么要提供部分功能来在运行时映射抛出而不是产生编译错误?

为什么 `constexpr` 函数在编译和运行时会产生不同的结果?

Micronaut中的DI错误在运行时而不是编译时出现?

Clojure-如何在运行时而不是编译时评估def形式

为什么在编译时不检查空指针异常,例如在Java中迭代空集合而不是运行时异常时?

使用非可比较类创建TreeSet:为什么运行时异常而不是编译时错误?

在运行时解析函数,而不是在编译 C++

C ++:在编译时(而不是在运行时)进行int计算

为什么在执行或运行时而不是在解析时设置IDENTITY_INSERT?

类内成员初始化是在编译时还是在运行时进行?

为什么Typescript类中的这种结构在编译时会很好地导致运行时错误?

为什么NullPointerException是运行时异常而RemoteException不是?

为什么当我用constexpr执行代码时,有时在编译时求值,有时在运行时求值?

当(大多数)其他检查在编译时发生时,为什么Rust在运行时检查数组范围?

为什么此记录结构正在编译但出现运行时错误

为什么在编译时无法解决运行时多态性?

为什么在编写编译器时需要运行时库?

为什么“ http.Get()”方法在运行时引发致命异常?

为什么此Typescript接口在运行时捆绑中导致空异常?

为什么在运行时出现Typescript编译错误?

为什么格式错误的XAML似乎会编译,然后在运行时失败?

在编译时运行的代码与在运行时运行的代码

使用Java在运行时编译Groovy类

使用Dart在运行时/编译时生成类

在运行时编译排除CodeDom生成的类

Java中的Arith Overflows:为什么在运行时没有异常并且没有编译器警告?

为什么在运行时加载OpenGL函数而不是动态链接?