4

checked block is used to make sure if overflow happens, an exception is thrown. For example,

The below code throws overflow exception which is fine.

checked
{
  int a = 123456;
  int b = 123456;
  Console.WriteLine(a * b);
}

But if I call a method inside the checked block, and the method in turn has code which is throwing overflow exception, checked block doesn't seem to detect that. Is it possible to detect these as well.

checked
{
  int a = 123456;
  int b = 123456;
  Console.WriteLine(Mul(a, b));
}

public int Mul(int a, int b)
{
  return a * b;
}
Mohammad Nadeem
  • 9,134
  • 14
  • 56
  • 82

1 Answers1

2

This Blog post gives some explanation about this topic:

https://devblogs.microsoft.com/oldnewthing/20140815-00/?p=233

In short: Whether a statement is executed in checked or unchecked mode is detected at compile time and not at runtime. If your program flow leaves the checked block including function method calls then the checked/unchecked state is specific to the function itsself.

The Mul method could be called from checked and unchecked code - Like this:

checked
{
     int a = 123456;
     int b = 123456;
     Console.WriteLine(Mul(a, b));
}
unchecked
{
     int a = 123456;
     int b = 123456;
     Console.WriteLine(Mul(a, b));
}

How should the exception behaviour be implemented ? Throw an exception or not ?

So you have to be specific in the Mul method and create a checked block there as well.

public int Mul(int a, int b)
{
   checked {
       return a * b;
   }
}
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Ralf Bönning
  • 14,515
  • 5
  • 49
  • 67
  • This is correct, but I just want to add that return values from functions that are inside of Check Blocks ARE still inside the Checked Context - for example: ` static int MethodA(){ checked{ int maxInt = int.MaxValue; return maxInt + SimpleAdditionMethod(5, 5); } }` - Exception thrown - Where SimpleAdditionMethod just returns the addition of its two parameters. But, if the parameters of SimpleAdditionMethod were (int.MaxValue, 1) - No Exception thrown, because that method returns a value of -2147483648, and then MethodA would return a value of -1. – DP3PO Jul 25 '22 at 18:07