2017-06-06 7 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

リターン 'MUL()' doesnの場合がありますことを意味例外 – stuartd

+1

をキャッチ後の値'戻り値'。あなたのコードが何をしているかを考えれば、簡単に見つけることができます。 –

+0

「キャッチ」内に2回目の 'return'を追加すると、すべての回答にtry-catchブロックの外側に1つの' return'を置くことができます(普通は私がします) – Veverke

答えて

0

mul()例外がキャッチされたときに値を返しません。 catchブロックまたはメソッドの最後にreturnのステートメントを追加します。

例外がスローされ
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値を返すか、投げる必要があるため)shortはそうあなたがcatchでいくつかの値を返す必要がある:あなたがcatchブロックから例外をスローする必要が

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

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

    throw; 
} 
0

。たとえば:

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

これはOPコンパイルの問題を解決しますが、それでも良いアドバイスではありません。それは特別な価値を確認する必要性を紹介します。さらに、負の数も可能である。 – sam

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); 
     } 
    } 
} 
関連する問題