如何在C#中处理OverflowException?

时间:2017-06-06 14:26:23

标签: c# .net exception-handling

我需要在方法mul()中处理OverflowException。

class B
{
    short a, b;
    public B(short a, short b) { this.a = a; this.b = b; }
    public short mul()
    {
        try
        {
            return checked((short)(a * b));
        }
        catch (OverflowException exc) { Console.WriteLine(exc); }
    }
}

class MainClass
{
    public static void Main(string[] args)
    {
        B m1 = new B(1000, 500);
        m1.mul();
    }
}

但是上面的代码给出了以下错误:错误CS0161:'B.mul()':并非所有代码路径都返回一个值(CS0161)

我该怎么做才能解决它?

4 个答案:

答案 0 :(得分:4)

不要混合逻辑和UI;只需将try {} catch {}放到适当的位置,一切都会清楚:

class B 
{
    ...

    // Logic: multiply with possible Overflow exception
    // Let us be nice and document the exception 
    ///<exception cref="System.OverflowException">
    ///When a or (and) b are too large
    ///</exception> 
    public short mul()
    {
        // Do we know how to process the exception at the place? 
        // No. There're many reasonable responses: 
        // - stop execution
        // - use some special/default value (e.g. -1, short.MaxValue)   
        // - switch to class C which operates with int (or BigInteger) etc.
        // That's why we don't catch exception here  
        return checked((short)(a * b));
    }
}

...

class MainClass
{
    // UI: perform operation and show the result on the console
    public static void Main(string[] args)
    {
        B m1 = new B(1000, 500);

        try 
        { 
            m1.mul();
        }
        catch (OverflowException exc) 
        { 
            // Proper place to catch the exception: only here, at UI, 
            // we know what to do with the exception:
            // we should print out the exception on the Console
            Console.WriteLine(exc); 
        } 
    }
}

答案 1 :(得分:1)

当抛出异常时,你会向控制台写一些内容但不返回任何值。

您的方法返回值为short,因此您应该在catch中返回一些值(因为方法应该在每个执行路径中返回一些short值或抛出):

try 
{
    return checked((short)(a * b)); 
}

catch(OverflowException exc) 
{
    Console.WriteLine(exc);

    throw;
}

答案 2 :(得分:0)

捕获异常时,

mul()不返回值。将return语句添加到catch块或方法的末尾:

public short mul()
{
    try {
        return checked((short)(a * b)); }
    catch(OverflowException exc) {
        Console.WriteLine(exc);
        return 0; // or whatever
    }
    return 0; // this goes as well
}

答案 3 :(得分:0)

你必须从catch块中抛出异常。例如:

catch(OverflowException exc) 
{
    Console.WriteLine(exc)
    throw exc;
}