Ruby编程:异常处理、对象与类的深入解析
1. 异常处理
在编程过程中,异常处理是必不可少的一部分。Ruby 提供了强大的异常处理机制,类似于 C# 和 VB。
1.1 捕获异常
在 C# 和 VB 中,通常使用 try-catch 语句来捕获异常,示例如下:
- C# :
int a = 5;
int b = 0;
int div;
try
{
div = a / b;
Console.WriteLine("This is never written");
}
catch (Exception ex)
{
Console.WriteLine("Oops... {0}", ex.Message);
}
- VB :
Dim a As Integer = 5
Dim b As Integer = 0
Dim div As Integer
Try
div = a / b
Console.WriteLine("This is never written")
Catch ex As Exception
Console.WriteLine("Oops... {0}", ex.Message)
End Try
在 Ruby 中,使用 begin-rescue
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



