2017-06-06 58 views
0

我需要在mul()方法中處理OverflowException。如何處理C#中的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)

我能做些什麼來解決這個問題?

+0

返回捕捉異常 – stuartd

+1

這意味着,還有的地方'MUL()'沒有按的情況下,後一個值't'返回'一個值。如果想想你的代碼的功能,很容易找到。 –

+0

所有的答案都提到在catch中添加第二個'return' - 你也可以有一個'return',在try/catch塊外部(通常我是這麼做的) – Veverke

回答

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 
} 
1

當異常被拋出,你寫的東西來安慰,但不返回任何值。

你的方法的返回值是short所以你應該在catch返回一些值(因爲方法應在每個執行路徑返回一些short的值或者拋出):

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

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

    throw; 
} 
0

你不得不放棄從catch塊的異常。例如:

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

這將解決OP編譯問題,但仍不是一個好建議。它引入了檢查特殊值的需求。此外,負數可能被允許。 – sam

4

請別不能混合邏輯和用戶界面;只是把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); 
     } 
    } 
}