0 java
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
str = br.readLine();
i = Integer.parseInt(str);
} catch(NumberFormatException e) {
System.out.Println("enter a valid input");
}
Run Code Online (Sandbox Code Playgroud)
当我尝试编译此代码时,它会抛出一个编译错误,ioexception正在发生我应该抓住它.
因此我必须添加一个catch(IOException e)语句,但发生的异常是java.lang库的数字格式异常,所以我为什么要捕获ioException.
str=br.readLine();
Run Code Online (Sandbox Code Playgroud)
BufferedReader.readLine()抛出 IOException.
public String readLine() throws IOException
Run Code Online (Sandbox Code Playgroud)
抛出:IOException - 如果发生I/O错误
因为IOException是一个已检查的异常,您需要使用try/catch块处理它或使用throws子句声明它.
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
str=br.readLine();
i=Integer.parseInt(str);
}catch(IOException e)
{System.out.println("IOException occured... " + e.printStacktrace());
catch(NumberFormatException e)
{System.out.println("enter a valid input");
}
Run Code Online (Sandbox Code Playgroud)
在java 7中多次捕获:
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
str=br.readLine();
i=Integer.parseInt(str);
}
catch(IOException | NumberFormatException ex) {
System.out.println(ex.printStackTrace())
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1204 次 |
| 最近记录: |