我无法在下面的代码中解决以下异常.我使用BufferedReader的方式有什么问题?我在main方法中使用BufferedReader
输出: -
ParseFileName.java:56: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
BufferedReader buffread = new BufferedReader (new FileReader("file.txt"));
Run Code Online (Sandbox Code Playgroud)
// ParseFileName is used to get the file name from a file path
// For eg: get - crc.v from "$ROOT/rtl/..path/crc.v"
import java.util.regex.Pattern;
import java.io.*;
public class ParseFileName {
//Split along /'s , and collect the last term.
public String getName (String longName) {
String splitAt = "/";
Pattern pattern1 = Pattern.compile(splitAt);
String[] parts = pattern1.split(longName);
System.out.println("\nparts.length = …Run Code Online (Sandbox Code Playgroud) 我是Java初学者,并且知道try...catch语句用于处理异常; 表示当try块抛出异常时,catch执行块.所以,我的问题是,当我尝试下面的代码(没有try catch)它抛出一个未报告IOException的read()方法,但当我使用 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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我认为编译器会抛出一个异常,这就是代码与try catch一起工作的原因.但是为什么不执行catch块呢?我得错了.
在以下示例中,Eclipse不要求我添加“ throws EmptyStackException”
public E pop() {
if (stack.isEmpty()) {
throw new EmptyStackException();
}
...
}
Run Code Online (Sandbox Code Playgroud)
但是,在以下示例中,“ throw Exception”是必需的
public E pop() throws Exception {
if(stack.isEmpty()) {
throw new Exception();
...
}
Run Code Online (Sandbox Code Playgroud)
关于何时应该添加引发的任何特定规则?
Exception 和 RuntimeException 都继承自 Throwable 并且没有实现任何接口来判断它们是否被检查。
哪里指定了 Exception 被检查并且 RuntimeException 未被检查?它是在语言或 JVM 中硬连线的吗?
我需要对String表示日期的列表进行排序.
我尝试了以下代码:
try {
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
Collections.sort(days,
(s1, s2) -> sdf.parse(s1).compareTo(sdf.parse(s2)));
} catch (ParseException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
但在Eclipse中我得到编译时错误sdf.parse(s1):
未处理的异常类型
ParseException
有解决方案吗
我的输入列表是:
[2016-01-02, 2016-01-03, 2016-01-01]
Run Code Online (Sandbox Code Playgroud) 我最近一直在做一些纯Java开发,我正在使用一个暴露少量方法的外部库,每个方法都有可能抛出一个Exception.
Eclipse不会让我编译我的程序,除非我将每个调用包装在一个try-catch块中.到目前为止,没什么大不了的.
然后我注意到了一些东西,比如ArrayList.add()抛出的东西IndexOutOfBoundsException.我怎么称呼这样的东西而不需要把它包裹起来try..catch呢?Obv,在这种特殊情况下,如果每次都必须这样做,那将是非常恼人的,但是try-catch在某些情况下是如何以及为什么强制实施的,而不是其他情况?
您如何编写在方法声明中具有“throws IllegalArgumentEception”的方法。比如这个:如果我只在 d>0 时返回 d 否则抛出 an IllegalArgumentException,我该怎么做?你使用try{}和catch{}吗?
public double getPrice(double d) throws IllegalArgumentException {
}
Run Code Online (Sandbox Code Playgroud) java ×7
exception ×4
date ×1
file ×1
filereader ×1
ioexception ×1
java-io ×1
sorting ×1
throws ×1