BOO大全/例外处理

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

上一章:自订宏 目录 下一章:Windows Form


例外处理[编辑]

在现代语言里,处理错误多半建议使用例外处理。例外处理的代码将会在例外发生时,发生作用,而这部分代码与你正常的程式处理是分开的。

语法与 Python 相近,任何你想要保护的代码都放在 try 区块里,而处理错误的代码则放在 except 区块里。

str as string
try:
  str = str.ToUpper()
except:
  print "something happened!"

如果例外发生了,那么try将会捕捉例外,所以使用者将不会看到令人生惧的死亡对话框。

通常也会需要知道是发生了哪一种例外:

import System
str as string
try:
  str = str.ToUpper()
except e as NullReferenceException:
  print "str was null",e.Message
except e as Exception:
  print "something weird happened!",e.Message

try 区块之后可以有多个例外处理区块,一般会把最常见的例外放到前面。


上一章:自订Macro 目录 下一章:Windows Form