Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the significance of using checked here

Tags:

c#

.net

Can anyone elaborate following statement:

byte[] buffer = new Byte[checked((uint)Math.Min(32 * 1024, (int)objFileStream.Length))];  

why i should not use

byte[] buffer = new Byte[32 * 1024];  
like image 802
donstack Avatar asked Apr 04 '13 09:04

donstack


People also ask

When should we use checked exception?

“If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.” In this way, we can recover the system by accepting another user input file name.

Why do we use checked exceptions in Java?

In broad terms, a checked exception (also called a logical exception) in Java is something that has gone wrong in your code and is potentially recoverable. For example, if there's a client error when calling another API, we could retry from that exception and see if the API is back up and running the second time.

What is an example of a checked exception?

ClassNotFoundException, IOException, SQLException etc are the examples of the checked exceptions.

What is checked exception?

A checked exception is a type of exception that must be either caught or declared in the method in which it is thrown. For example, the java.io.IOException is a checked exception. To understand what a checked exception is, consider the following code: Code section 6.9: Unhandled exception.


1 Answers

Attempt was to throw exception if objFileStream.Length will return number greater then int.MaxValue (2147483647), because Length on Stream returns long type (I assume objFileStream is stream). In .net arithmetic overflow is not checked by default.

Next code demonstrates this case:

long streamLength = long.MaxValue; //suppose buffer length is big

var res = checked( (int)(streamLength + 1) ); //exception will be thrown

Console.WriteLine( res ); //will print 0 in you comment checked keyword 

After short analysis, you can reduce next statement

new Byte[checked((uint)Math.Min(32 * 1024, (int)objFileStream.Length))]; 

to

new Byte[Math.Min(32 * 1024, checked((int)objFileStream.Length))];

Personal recommendation: I don't see how OverflowException will help you here. Math.Min will ensuse, that array will be created no longer than 32768 items. If you try to catch somewhere in the calling method, you won't be able to deduce what is the reason of that error, it may come from anywhere in the called stack.

So you probably need not to always allocate array of size 32768 as you proposed

byte[] buffer = new Byte[32 * 1024]; 

but still use Math.Min so that you'll save storage, if objFileStream.Length will return small number

byte[] buffer = new Byte[Math.Min(32 * 1024, objFileStream.Length)]; 
like image 116
Ilya Ivanov Avatar answered Oct 06 '22 00:10

Ilya Ivanov