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
  • 8,798
  • 14
  • 54
  • 80

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
  • 5,793
  • 5
  • 23
  • 56
Ralf Bönning
  • 13,574
  • 5
  • 47
  • 66