我有一个程序,它接受用户关于游戏对象的信息,然后将游戏对象数组写入文件。我还需要使用我创建的异常类。如果用户输入的文档代码不是Sp、St或Gh,则需要抛出异常并捕获并处理,以允许用户尝试输入正确的代码。我认为我的异常类是正确的,但我真的不知道如何实现它。
public class InvalidDocumentCodeException extends Exception //Here is my exception class
{
public InvalidDocumentCodeException (String message)
{
super (message);
}
}
import java.util.Scanner;
import java.io.*;
public class GamesList
{
public static void main (String[] args) throws InvalidDocumentCodeException, IOException
{
Scanner scan = new Scanner (System.in);
int count = 0, year;
String doMore = "y";
String file = "GameInfo.dat";
String documentCode, title, developer;
double price;
FileWriter fw = new FileWriter (file);
BufferedWriter bw = new BufferedWriter (fw);
PrintWriter outFile = new PrintWriter (bw);
//don't know if I need this
InvalidDocumentCodeException problem = new InvalidDocumentCodeException ("Incorrect document code!!!");
GameCollection games = new GameCollection();
while (doMore.equalsIgnoreCase("y")) //lets user input data until they are done
{
System.out.println("Enter a valid document code (Sp, St, Gh):");
documentCode = scan.nextLine();
try //my try catch
{
documentCode = "Sp";
}
catch(InvalidDocumentCodeException)
{
System.out.println("Oops! Try a valid code:");
documentCode = scan.nextLine();
}
System.out.println("Enter the game name:");
title = scan.nextLine();
System.out.println("Enter the game developer:");
developer = scan.nextLine();
System.out.println("Enter the games release year:");
year = scan.nextInt();
System.out.println("Enter the games price:");
price = scan.nextDouble();
games.addGame(documentCode, title, developer, year, price);
System.out.println();
System.out.println("This is great. Let's enter some more data. (Y/N):");
doMore = scan.next();
scan.nextLine();
}
outFile.println(games);
System.out.println("Data written to GameInfo.dat");
System.out.println(games);
outFile.close();
}
}
我环顾四周,但也许我只是不明白异常和 try catch 语句如何工作得足够好。
最佳答案
通常,您可以在需要的时间和地点创建并抛出异常。因此,例如,您可以这样:
try {
// Do something
if (somethingIsWrong) {
throw new MyException("This is broke, yo!");
}
} catch(MyException me) {
// Write code to handle the exception or log it...
}
另一种方法是调用抛出异常的方法:
try {
callToMethodThatThrowsSomeException(someVal);
} catch(SomeException se) {
// Handle the exception here...
}
其中 callToMethodThatThrowsSomeException(someVal)
看起来像:
public void callToMethodThatThrowsSomeException(String someVal) throws SomeException {
// Your code here, throwing a new SomeException for some reason...
}
在这种情况下,SomeException
将扩展 Exception
。您可以让它扩展RuntimeException
,在这种情况下,您不需要在方法签名上声明抛出。
关于java - 如何使用异常类,在主程序中捕获并处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22256282/