为什么0除以0会在VBA中引发溢出错误? [英] Why is 0 divided by 0 throwing an overflow error in VBA?

查看:444
本文介绍了为什么0除以0会在VBA中引发溢出错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么0/0在VBA中抛出Overflow error,而在.Net语言中,它仅仅是一个Division by 0错误?

Why is 0/0 throwing Overflow error in VBA, while in .Net languages it is simply a Division by 0 error?

例如,在C#中是System.DivideByZeroException

static void Main()
{
    int k = 0;
    int p = 0;
    Console.WriteLine(k/p);
}


中存在

Div/0错误. 但是 0/0给出了溢出异常,而除以0的其他任何东西都给出了Div/0异常:


Div/0 error exists in VBA. But 0/0 gives an overflow exception, while anything else divided by 0 gives a Div/0 exception:

Public Sub TestMe()

    'Integer
    PrintAndCheck (11)      '- Division by zero error

    'Double
    PrintAndCheck (0.9)     '- Division by zero error

    'Long
    PrintAndCheck (50000)   '- Division by zero error

    'String
    PrintAndCheck ("1.1")   '- Division by zero error

    '----------------------------------------------------
    '----------------BUT---------------------------------
    '----------------------------------------------------

    'Integer
    PrintAndCheck (0)       '- Overflow?

End Sub

Public Sub PrintAndCheck(lngDivisor As Variant)

    On Error Resume Next

    Debug.Print lngDivisor / 0
    Debug.Print Err.Description & " from type -> " & VarType(lngDivisor)

    On Error GoTo 0

End Sub

这就是您在即时窗口中看到的内容:

That's what you get in the immediate window:

Division by zero from type -> 2
Division by zero from type -> 5
Division by zero from type -> 3
Division by zero from type -> 8
Overflow from type -> 2

使整个故事更有趣:

Public Sub TestMe()
    On Error Resume Next
    Debug.Print Evaluate("0/0")     'Division by 0 error (CVErr(xlErrDiv0)=2007)
    Debug.Print 0 \ 0               'Division by 0 error
    Debug.Print Err.Description
    On Error GoTo 0
End Sub

推荐答案

将尝试总结评论中的答案:

Will try to summarize the answers from the comments:

  1. 在VBA中, 0/0 会引发溢出异常,因为 0/0 是除以 0 的特定情况.因此,最好抛出与标准Division by zero error不同的异常.

  1. In VBA 0/0 throws an Overflow exception, because 0/0 is a specific case of division by 0. Thus, it is a good idea to throw a different exception than the standard Division by zero error.

在VBA中,Evaluate("0/0")返回Division by zero error,因为Evaluate不会引发错误,它返回带有错误标志的Variant值,并且没有可用的溢出"标志.

In VBA Evaluate("0/0") returns a Division by zero error, because Evaluate does not raise an error, it returns a Variant value with an error flag, and there is no "overflow" flag available.

在VBA整数除法中, 0 \ 0 返回Division by zero error,因为结果应为整数值,而#IND为浮点值.就无法返回#IND而言,它提供了下一个最好的选择-Division by zero error.

In VBA integer division 0\0 returns a Division by zero error, because the result should be an integer value and #IND is a floating point value. As far as #IND cannot be returned, it gives the next best thing - Division by zero error.

有关其他语言中的 0/0 的更多阅读内容:

More reading concerning 0/0 in other languages:

查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆