我正在实现一个try catch块,以便在从文件读取数据之前确认该文件存在,然后使用该数据打印出一个菜单,最终运行一个菜单驱动的应用程序。看起来好像我正确地读取了文件,但是,当我运行驱动程序类时,它会显示catch块中包含的错误消息,然后才会正确显示所需的输出菜单。
public static void main(String[] args)
{
try
{
Scanner input = new Scanner(new File("concerts.txt"));
ConcertEvent concert1 = new ConcertEvent(input);
ConcertEvent concert2 = new ConcertEvent(input);
ConcertEvent concert3 = new ConcertEvent(input);
System.out.println("Redbird Concert Hall");
System.out.println();
System.out.println("Please choose your concert:");
System.out.println("1. " + concert1.getBandName());
System.out.println("2. " + concert2.getBandName());
System.out.println("3. " + concert3.getBandName());
System.out.println("4. Quit");
System.out.println();
}
catch(Exception e)
{
System.out.println("Error: File Not Found");
}我附加了用于创建ConcertEvent的三个实例的构造函数
public ConcertEvent(Scanner input)
{
try
{
bandName = input.nextLine();
showCapacity = input.nextInt();
ticketPrice = input.nextDouble();
input.nextLine();
}
catch(Exception e)
{
System.out.println("Error: file not found");
}
}所需输出:
Redbird Concert Hall
Please choose your concert:
1. Maroon 5
2. One Direction
3. Pearl Jam
4. Quit实际输出:
Error: file not found (Exception found in the catch statement of the
Redbird Concert Hall
Please choose your concert:
1. Maroon 5
2. One Direction
3. Pearl Jam
4. Quit我意识到在构造函数中使用try catch块可能是不正确的,但是当我删除try catch块时,实际输出变为...
错误:找不到文件(在main方法的catch语句中发现的异常)
发布于 2013-11-17 06:47:02
触发的catch块是您的ConcertEvent构造函数中的块,可能是找不到文件或无法访问,等等(只有打印堆栈跟踪才能知道)。
如果您希望提示符输出在任何文件操作之前发生,只需将其移动到main方法中的try块之前。
此外,正如Chandranshu提到的那样,捕获特定的异常将帮助您确定问题。
最后,让您的main方法为同样具有try/catch语句的构造函数声明try/catch语句没有多大意义,这对于相同的Exception是合理的。
在构造函数中删除Exception,或者删除main方法中的try/catch。
例如,由于FileNotFoundException是一个检查过的异常,您可以在构造函数中对其进行throw (并且必须在其签名中声明一条语句),然后在< throws >d24catch >中在main中对其进行printStackTrace,然后在catch语句中对其进行printStackTrace)。
https://stackoverflow.com/questions/20024756
复制相似问题