我正在尝试学习Java中的“带有异常的错误处理”。
我知道有关它的一件令人惊奇的事情,就是您可以只在一个地方处理一个Exception,并且只要在该部分中抛出该异常,它就会被捕获,所以我有这段代码,我想回到解决ReservationManager()
中catch块中的InputMismatchException
异常后的main
。
实际上,现在当用户在ReservationManager
节中键入字符串而不是整数时,程序将返回到
Please select: To book or return the room: 1To Exit: 0
但我想打印
Please select: To book a room: 1 To check out: 2 To Exit: 3
实际上,我想在main中的catch块之后返回
ReservationManager
。我在名为
hotel
的类中具有这部分代码: public static void main(String[] args) {
Hotel hotel = new Hotel(5);
int serviceNumber;
System.out.println("Welcome");
Formatter f = new Formatter(System.out);
Map <Integer, String> whatService = new LinkedHashMap<>(); //list of model services
whatService.put(1,"b.a.service.ReservationManager");
while (true) {
Scanner scanner = new Scanner(System.in);
try {
f.format("%s\n %40s\n %21s\n", "Please select:", "To book or return the room: 1", "To Exit: 0");
serviceNumber = scanner.nextInt();
if(serviceNumber != 0) {
Class c = Class.forName(whatService.get(serviceNumber)); //using RTTI!
c.newInstance();
}
else {
System.exit(0);
}
} catch (NullPointerException e){
System.out.println("---Please Choose from the options!---");
} catch (ClassNotFoundException e) {
System.out.println("ClassNotFoundException");
} catch (IllegalAccessException e) {
System.out.println("IllegalAccessException");
} catch (InstantiationException e) {
System.out.println("InstantiationException");
}catch (InputMismatchException e) {
System.out.println("---Please enter a number!---");
}
}
}
这是名为ReservationManager的类中的该部分,如果用户首先输入“1”,则会创建该类。
public ReservationManager() throws Exception{ //constructor
System.out.println("Welcome to reservation section");
int service = 0;
Formatter f = new Formatter(System.out);
while(true){
Scanner scanner2 = new Scanner(System.in);
f.format("%s\n %28s\n %26s\n %21s\n","Please select:","To book a room: 1", "To check out: 2", "To Exit: 3");
service = scanner2.nextInt();
switch (service) {
case 1:
bookingHotelRooms();
break;
case 2:
System.out.println("Please Enter the room number");
checkout(scanner2.nextInt());
break;
case 3:
System.exit(0);
break;
}
}
}
提前致谢。
最佳答案
我想,我找到了答案。关键是我犯了一个小错误,我认为最好只在一个地方处理一个Exception,并且不应该在程序中重复相同的try_catch,但这是不正确的,实际上不像它处理不好在程序中不同位置具有相同的异常,这对于查找异常的确切位置也很有帮助。因此,我将在“ReservationManager”中编写相同的try-catch并在其中处理“InputMismatchException”,使其与我的“main”相同,但最好显示一些有关确切位置的信息(可能是通过记录器)。
关于java - 在Java中捕获先前方法(2)中的异常后,如何返回原因方法(1)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45917345/