Exception handling
Exception handling enables a program to deal with exceptional situations and continue its normal execution. In Java, runtime errors are thrown as exceptions. An exception is an object that represents an error or a condition that prevents execution from proceeding normally. If the exception is not handled, the program will terminate abnormally. How can you handle the exception so that the program can continue to run or else terminate gracefully?(在Java中,异常处理是指将程序运行中发生的异常或错误作为对象抛出并进行处理的过程,异常处理使得程序在发生异常后能继续执行或“温和”地终止)
Case Study
Inputting method without exception handling.

当输入不合法时,程序发生异常终止

Inputting method with exception handling.

input.nextInt()函数执行时,可能会抛出InputMismatchException类型的异常。为避免输入不合法时程序异常终止,这里需要用try-catch语句对该类异常进行捕获和处理,处理方式有两种:一是捕获到异常后打印提示信息,让程序自然终止;二是捕获异常后让用户重新输入,直到输入正确。这里借助do-while循环采用了第二种异常处理方式,其运行效果如下


