异常

异常处理的写法

begin
    可能发生异常的代码
rescue => 引用异常对象的变量
    发生异常时的处理
end
begin
rescue Exception1, Execption2 => 变量
    对这两种异常的处理
rescue Exception3 => 变量
    对Exception3的处理
rescue
    发生其他异常时的处理
end

异常发生时被自动赋值的变量 变量 | 意义 --|-- $! | 最后发生的异常(异常对象) $@ | 最后发生异常的位置信息

异常对象的方法

方法名 意义
class 异常的种类
message 异常信息
backtrace 异常发生的位置信息($@与 $!.backtrace等价)

实例

def open file
  begin
    io = File.open(file)
  rescue => ex
    p ex.message
    #p $!.message
    #也可以
    #=> "No such file or directory - /home/aaron/test.txt"

    #p ex.class
    #=> Errno::ENOENT
  end
end

open "/home/aaron/test.txt"

后处理

不管异常是否发生,都会执行

def open file
  begin
    io = File.open(file)
  rescue => ex
    p ex.message
  ensure
    p '我一定会运行'
  end
end

open "/home/aaron/test.txt"

#=> "No such file or directory - /home/aaron/test.txt"
#=> "我一定会运行"

重试

def open file
  begin
    io = File.open(file)
  rescue
    sleep 10
    #小心死循环
    retry
  end
end

rescue修饰符

表达式1 rescue 表达式2

#等价于

begin
    表达式1
rescue
    表达式2
end
n = Integer(val) rescue 0
=begin
如果Integer接收到数字,则把整数赋值给n
如果接收到的是字符串,则抛出异常,把 0 赋值给n
=end

异常类

Exception
    SystemExit
    NoMemoryError
    SignalException
    ScriptError
        LoadError
        SyntaxError
        NotImplementedError
    StandardError
        RuntimeError
        SecurityError
        NameError
            NoMethodError
        IOError
            EOFError
        SystemCallError
            Error::EPERM
            Error::ENOENT

主动抛出异常

用法 意义
raise message 抛出RuntimeError异常,并把字符串作为message设置给新生成的异常对象
raise 异常类 抛出指定的异常
raise 异常类, message 你懂的
raise 在rescue外抛出RuntimeError。在rescue中调用,会抛出最后一次发生的异常($!)