BOO入门/例外

维基教科书,自由的教学读本

BOO入门 > 例外 (上一章:列举 下一章:将函数当作物件与多执行绪)


定义 定义 例外:在电脑程序里用来处理执行时期错误或其他问题的方法。

例外非常重要,每当系统发生错误时,例外就会被提出。

捕捉例外[编辑]

如果没有捕捉到例外的话,程序将会被中止。

// Division by Zero
print 1 / 0

输出结果

System.DivideByZeroException: Attempted to divide by zero.
   at Test.Main(String[] argv)

这个例外造成程序中止。

要处理这种情形,我们得捕捉例外。我们可以使用 try-except 述句、try-ensure 述句或者是 try-except-ensure 述句。所有的例外都继承自 Exception 类别。

// try-except 範例
import System

try:
    print 1 / 0
except e as DivideByZeroException:
    print "Whoops"
print "Doing more..."

输出结果

Whoops
Doing more...

如你所见到,在捕捉例外之后,程序不会因为错误而中止,仍旧继续执行。

捕捉错误并不只限于一个,你可以写多个 except 来捕捉多种例外。

Try-ensure 用在确保某些事情能完成,不管错误有没有发生。

// try-ensure 範例
import System

try:
    s = MyClass()
    s.SomethingBad()
ensure:
    print "This code will be executed, whether there is an error or not."

输出结果

This code will be executed, whether there is an error or not.
System.Exception: Something bad happened.
   at Test.Main(String[] argv)

从上面例子你可以看到,ensure 区块里的程式不管错误有没有发生都会被执行。

而 try-except-ensure 则结合两者:

// try-except-ensure 範例
import System

try:
    s = MyClass()
    s.SomethingBad()
except e as Exception:
    print "Problem! ${e.Message}"
ensure:
    print "This code will be executed, whether there is an error or not."

输出结果

Problem: Something bad happened.
This code will be executed, whether there is an error or not.
建议 建议 如果你不打算在 except 述句里解决问题,你可以使用 raise (下节会介绍)不带任何参数再把原来的例外提出,让后续的程序去处理。

提出例外[编辑]

或许你会想提出自己的例外,这时候可以使用 raise 关键字。

// 提出例外
import System

def Execute(i as int):
    if i < 10:
        raise Exception("引數 i 必須大於或等於 10")
    print i

当传入不适当的值给 Execute 时,例外将会被提出。

建议 建议 在正式上线的环境下,你应该建立自己的例外,即使这个例外只是包裹标准的 Exception 类别然后换个名字而已。
建议 建议 永远别使用 ApplicationException 。

译注:原文为 Raising Exceptions,C++ 用 throw,因此可以用掷出例外或丢出例外,用 Raise,我想用提出例外或许比较好。

练习[编辑]

  1. 试着去捕捉多个例外看看
  2. 试着继承 Exception,并且提出(raise)