我正在尝试 Java 的异常处理。
我无法从文档中理解如何执行此操作,但我想做的是检测我的开关的无效输入,以便在激活默认情况时抛出错误。这对我来说可能是不正确的逻辑,但我想知道是否有人可以用简单的英语将我推向正确的方向。
char choice = '0';
while (choice != 'q'){
printMenu();
System.in.read(choice);
case '1': DisplayNumAlbums();
case '2': ListAllTitles();
case '3': DisplayAlbumDetail();
case 'q': System.out.println("Invalid input...");
return;
default: System.out.println("Invalid input...");
//Exception handling here
//Incorrect input
}
我假设您的错误是经过深思熟虑的,因此我将使用您自己的代码来制作您要求的用法示例。因此,拥有一个正在运行的程序仍然是您的责任。
异常处理机制是为了让您在达到某些错误条件时抛出异常,就像您的情况一样。假设您的方法名为 choiceOption
,您应该这样做:
public void choiceOption() throws InvalidInputException {
char choice = "0";
while (choice != "q"){
printMenu();
System.in.read(choice);
switch(choice){
case "1": DisplayNumAlbums();
case "2": ListAllTitles();
case "3": DisplayAlbumDetail();
case "q": System.out.println("Invalid input...");
return;
default: System.out.println("Invalid input...");
throw new InvalidInputException();
}
}
}
这让您可以在客户端捕获抛出的异常(您拥有的任何客户端:文本、胖客户端、Web 等)并让您采取自己的客户端操作,即如果您使用的是 swing 或添加一个 JOptionPane如果您使用 JSF 作为 View 技术,则会面临消息。
请记住,InvalidInputException
是一个必须扩展 Exception 的类。