当找到文件但不包含任何内容时抛出哪个异常?

Which exception to throw when a file is found but does not contain anything?

如果文件为空,应该抛出哪个异常?

例如,

List<Cars> cars = new LinkedList<Cars>(); 

Scanner inFile = new Scanner(new FileReader(filename));

    if(!inFile.hasNextLine()) {
        throw new ???????????????????
    } 

    while(inFile.hasNextLine()) {
        String line = inFile.nextLine(); 

        String[] CarInfo = line.split("\|"); 

        Car tmpCar = new Car(CarInfo[0],CarInfo[1],CarInfo[2]);

        cars.add(tmpCar);

    } 
    inFile.close(); 

谢谢

您可以创建自己的例外。

class EmptyExceptoin extends Exception
    {

      public EmptyException() {}

      public EmptyException(List list)
      {
         super(list);
      }
 }

然后在您的代码中抛出异常:

   Scanner inFile = new Scanner(new FileReader(filename)); 

        if(!inFile.hasNextLine()) {
            throw new EmptyException();
        }

您可以使用自己的消息创建自己的自定义异常 class,如下所示:

public class EmptyFileException extends Exception {

    private String message = "The file is empty!";

    public EmptyFileException() {
        super(message);
    }

}

然后在你的代码中你可以抛出新的异常:

Scanner inFile = new Scanner(new FileReader(filename)); 

if(!inFile.hasNextLine()) {
    throw new EmptyFileException();
}
// ...

B.

当文件存在但为空时,标准 Java 库没有一般例外。

看起来这种情况对您的申请来说有些特殊。所以你可以通过扩展Exception class来创建你自己的异常类型。看这里 - How to create custom exceptions in Java?

您大致有两种可能性:

  • 抛出一个RuntimeException比如IllegalArgumentException如果异常无法从客户端恢复,请执行此操作。

  • 如果异常必须由客户端处理,则抛出自定义检查异常。例如EmptyFileExceptionpublic class EmptyFileException extends Exception{ }

创建一个继承自异常 class

的自定义异常 class
Class EmptyFileException extends Exception{
    public EmptyFileException(){
    }
    public EmptyFileException(String customMessage){
        super(customMessage)
    }
}

您可以在 try catch 或任何 if 语句中使用它

try
{
   //do stuff.....
}catch(Exception e){
   throw new EmptyFileException("File not found") 
}