Friday, 23 December 2011

C# Modulo Operator - Find easy the remainder of a division.






Percentage symbol



You want to see examples of the modulo division operation in the C# language, which allows you to execute code once every several iterations of a loop. The modulo operator uses the percentage sign % character in the lexical syntax and has some unique properties. Here we look at the modulo division operation.
Estimated costs of instructions

Add:         1 ns
Subtract:    1 ns
Multiply:  2.7 ns
Divide:   35.9 ns

Example 1

Thursday, 8 December 2011

c# How to Throw Exception and how to bubble up an Exception


problem

c# - How to throw exceptions, how to bubble up exceptions, how to digg exceptions to find deep error messages and Exceptions.
difficulty level

7/10 :|
compatibility

c#
solution

When you catch an Exception and you want to bubble up (forward) the same exception, you should bubble it up by your own, define it in the 2nd argument of your new Throw Exception. When you bubble up the Exception, you can find it as .InnerException.

try{
  int i=2/0;  //division by zero is not allowed anyway
} catch (Exception e) {
    throw new Exception(
        "Something get wrong, "+
        "error message: "+e.Message,
        e  // here we bubble up the exception
    );
}


The follow code demonstrates how car your dig the InnerException you find all error messages:

string output = "Error messages: ";
Exception exp = exceptionToBubble;
string expmessage = "";

while (exp != null) {
    expmessage = "inner error: " + exp.Message + " " + expmessage;
    exp = exp.InnerException;
}
expmessage += "final error: " + exceptionToBubble.Message;

output += expmessage;

Also, don't forget the .Trace property of the Exception object where show related info.