首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

CLisp 16:抛出和捕捉错误,try-catch机制

2012-09-04 
CLisp 16:抛出和捕捉异常,try-catch机制函数error用于抛出异常,带一个参数,可以是字符串,也可以像format一

CLisp 16:抛出和捕捉异常,try-catch机制

函数error用于抛出异常,带一个参数,可以是字符串,也可以像format一样拼字符串,也可以是一个异常对象,也可以是指向字符串或异常对

象的标识符,例如
(error "some error")
(setq x "some error")  (error x)
(setq y '(a b c)) (error "error info : ~A" y)

 

接下来用handler-case捕捉异常,类似于try-catch
(defun foo() (error "just wrong"))
(handler-case (foo)
  (error () "catch the error"))
运行后输出字符串catch the error,上面代码翻译成C++就是
try
{
   foo();
}
catch (error)
{
   return "catch the error";
}

 

除了基本的error类型,可以用define-condition定义新的异常类型
(define-condition log-entry-error (error)
  ((text :initarg :text :reader text)))
新类型名称是log-entry-error,它的父类是error,有一个参数text,该参数提供初始化方法和读方法。更多问题参考CLISP面向对象编程,定

义类的方法。
修改上面例子:
(defun foo() (error 'log-entry-error :text "just wrong"))
(handler-case (foo)
  (log-entry-error (e) (text e)))
翻译成C++就是
try
{
    foo();
}
catch (log-entry-error & e)
{
    return e.text();
}

 

如果在catch中同时安插error和log-entry-error类型,会出什么样的结果呢?将谁放前面就会匹配谁
(handler-case (foo)
  (error () "error")
  (log-entry-error () "log-entry-error))
匹配error类型,返回字符串error。

 

 

热点排行