C#中如何处理OverflowException?

0 .net c# exception

我需要在方法 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

但上面的代码给出了以下错误:Error CS0161: 'B.mul()': not all code paths return a value (CS0161)

我能做什么来修复它?

Dmi*_*nko 5

请不要混淆逻辑和 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));
    }
}
Run Code Online (Sandbox Code Playgroud)

...

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); 
        } 
    }
}
Run Code Online (Sandbox Code Playgroud)