如何在 Ruby 中处理异常


编程中的异常是在运行时发生的错误。它们很难有效地处理,但处理它们很重要,否则它们会中断程序执行。

一些常见的异常包括:

  • 尝试打开不存在的文件,

  • 除以零,

  • 内存不足等。

现在让我们来看几个例子,演示异常如何中断 Ruby 程序的执行。

示例 1

考虑以下代码。

Open Compiler
taking two integer value $First = 10; $Second = 0; # divide by zero error $Third = $First / $Second; puts "The Result is: #{$Third}"

在这个程序中,我们有两个整数,我们对它们进行除法运算,其中第二个整数是,这将导致异常。

输出

它将产生以下输出。

main.rb:1:in `
': undefined local variable or method `value' for main:Object (NameError)

我们在上面的例子中看到,由于代码中的一些错误,我们遇到一个异常,但我们甚至可以使用raise关键字创建我们自己的异常。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

示例 2

考虑以下代码。

Open Compiler
# defining a method def raising_exception puts 'Before Exception!' # using raise to create exception raise 'Exception Created' puts 'After Exception Arise' end # Calling the method raising_exception

在这个程序中,我们正在创建一个新的异常,然后我们在抛出异常的方法中添加两个日志。

需要注意的是,一旦遇到异常,之后就不会打印任何日志,因为程序会停止运行。

输出

它将产生以下输出。

Before Exception!
Traceback (most recent call last):
   1: from main.rb:13:in `<main>'
main.rb:7:in `raising_exception': Exception Created (RuntimeError)

示例 3

既然我们已经了解了异常的工作原理以及如何创建异常,让我们来看一个如何通过示例处理异常的例子。考虑以下代码

Open Compiler
# defining a method def rescue_from_raise begin puts 'Before Exception!' # using raise to create an exception raise 'Exception Created!' puts 'After Exception!' # using Rescue method rescue puts 'Saved!' end puts 'Outside!' end # calling method rescue_from_raise

输出

它将产生以下输出。

Before Exception!
Saved!
Outside!

更新于:2022年4月12日

浏览量 135 次

开启你的职业生涯

通过完成课程获得认证

开始学习
广告