Try/Catch Blocks and Following Statements
我的下面的代码存在一些问题。在此程序中,我输入了商品的描述,单位和价格。我创建了两个自定义异常类,以便用户输入负数。当我运行程序时,catch语句确实起作用,但是我发现奇怪的是,catch块之后的语句仍然执行。如果我错了,请纠正我,但是如果有异常,该程序不是不应该在catch语句之后执行语句吗?我的印象是,做到这一点的唯一方法是使用finally块。任何帮助将不胜感激!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | import java.util.Scanner; public class RetailItemDemo { public static void main (String[] args) { Scanner keyboard = new Scanner(System.in); RetailItem item = new RetailItem(); System.out.print("Item description:"); item.setDescription(keyboard.nextLine()); try { System.out.print("Units on hand:"); item.setUnitsOnHand(keyboard.nextInt()); System.out.print("Item price:"); item.setPrice(keyboard.nextDouble()); } catch (NegativeUnitsException nue) { System.out.println(nue); } catch (NegativePriceException npe) { System.out.println(npe); } System.out.println("\ The item is a " + item.getDescription()); System.out.println("There are" + item.getUnitsOnHand() +" units on hand"); System.out.println("The item price is" + item.getPrice() +"\ "); } } |
Correct me if I'm wrong, but isn't the program not supposed to execute
statements after the catch statement if there is an exception? I was
under the impression that the only way to do that was to use a finally
block.
恐怕你错了。
不管是否引发异常,都会执行
代码。这用于关闭需要清理的资源(例如打开的文件)。
如果要在引发异常后跳过所有内容,则没有必要使用
Java使用异常处理的终止模型,该模型的行为基本上与您所经历的相同:
further processing in that method is terminated and control is
transferred to the nearest exception handler that can handle the type
of exception encountered
from here: http://www.informit.com/articles/article.aspx?p=464630&seqNum=4.
当异常处理程序(catch块)完成处理后,在try / catch块之后的第一行代码处连续执行。
在异常处理的恢复模型中,在处理了异常之后,流程将返回引发异常的位置,并从该位置继续执行程序。
当某个方法在try块内引发异常时,它将跳过try块中的所有其他方法,执行catch块,然后从catch块后的下一行继续。
为防止这种情况,请将
如果您还有一个finally块,即使您在catch块中关闭程序,它也会被执行。
使用System.exit(0);在catch块中。