【问题标题】:why BufferedReader class producing Exception at compile time not at the run time为什么 BufferedReader 类在编译时而不是在运行时产生异常
【发布时间】:2015-09-10 10:03:43
【问题描述】:

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

所以这段代码编译成功,没有任何编译时java.lang.ArithmeticException: / by zero类型的异常,但只在运行时给出异常

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”在编译时而不是在运行时。

请告诉我为什么会这样?

【问题讨论】:

  • 不是异常,而是语法错误。请使用try...catchthrows 子句。

标签: java exception compilation bufferedreader ioexception


【解决方案1】:

由于IOException 是一个检查异常,您必须使用try...catch 或“throws”。

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

【讨论】:

  • 我在docs.oracle.com/javase/tutorial/essential/exceptions/… 阅读了文档,所以您说的是“异常 java.io.IOException;”是“BufferedReader”类的构造函数的“检查异常”,应在编译时解析。是吗?
  • 部分。 IOException 是一个检查异常,因为它扩展了java.lang.Exception,而不是java.lang.RuntimeExceptionBufferedReader.readLine() 抛出 IOException,应该使用 try...catch 捕获或使用 throws 重新抛出。
  • 我认为在编译时处理异常并不是强制性的,因为理论上说“异常发生在运行时”。那为什么 java.lang.Exception 中的异常要在编译时处理呢?
  • 您没有在编译时处理异常,您只是在编写代码以在运行时处理它。如果您碰巧在运行时遇到异常,此代码将保存您的应用程序以正常工作而不会突然终止。这就像在编译时编写代码来创建一个类的对象,但实际上对象是在运行时创建的。
  • 好的,我明白了,这只是一种预测此类情况并正确处理它们的方法,这样您的应用程序就不会崩溃hacktrix.com/checked-and-unchecked-exceptions-in-java
【解决方案2】:

readLine 的签名是这样的

public String readLine() throws IOException

因此,您必须处理它可能抛出的异常。将try/catchthrows IOException 添加到您的方法中。

在java中有已检查异常和未检查异常。这是一个检查异常,您必须以一种或另一种方式处理它。 ArithmeticException 是未经检查的异常的一个示例。

【讨论】:

  • 我仍然不清楚。请通过解释或任何示例让我理解@Simon
  • @G4uKu3 它是 java 语言的一部分。如果一个方法说它可能会抛出异常,那么您必须处理它,否则您的代码将无法编译。表示方法可能抛出异常的方式是在方法名称后添加throws SomeException
  • 我认为在编译时处理异常并不是强制性的,因为理论上说“异常发生在运行时”。
  • 是的,编译时不会发生异常。但是如果编译器发现你没有处理检查异常,那么你就会得到编译器错误。
  • 非常感谢您花时间和精力让我理解
猜你喜欢
  • 1970-01-01
  • 2011-02-22
  • 2011-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多