Archive

Archive for the ‘visualstudio’ Category

Visual Studio.NET and C #: how to handle exceptions and the line number of error

November 28th, 2010 No comments

The exception-handling features of C # allow you to handle unexpected or exceptional situations that occur during the execution of a program. In exception handling uses the try keyword, catch, and finally groped for performing actions that may fail, to handle errors and clean up after the resources. Exceptions can be generated by the common language runtime (CLR), from third-party libraries or application code using the throw keyword.

In this example, a method checks for division by zero error and notes. Without exception handling, the program would be terminated with an error like the following: DivideByZeroException was not handled.

int DivisioneSicura(int x, int)
{
    try
    {
        return (x / and);
    }
    catch (System.DivideByZeroException dbz)
    {
        System.Console.WriteLine("Warning division by zero!!!");

        // Print the error message System.Console.WriteLine(dbz.Message);

        // Print the line number of the source where the error is System.Console.WriteLine(dbz.StackTrace);

        return 0;
    }
}
return

Overview exceptions

The exceptions have the following properties:

  • When an exceptional circumstance occurs in the, such a division by zero or a problem of memory, is thrown.
  • Use a try block around the statements that might throw exceptions.
  • When an exception occurs inside the try block, the flow of control passes immediately to an exception handler associated, is present.
  • If for any exception handlers are not present, program execution will stop with an error message.
  • If an exception catch block defines a variable, You can use it to gain more information about the type of exception that occurred.
  • The actions that can throw a run with the try keyword.
  • An exception handler is a block of code that is executed when an exception occurs. For the definition of an exception handler, C # uses the catch keyword.
  • Exceptions can be generated explicitly by a program using the throw keyword.
  • The exception objects contain detailed information about, including the state of the call stack and a description of, then use to print the description of the education System.Console.WriteLine(dbz.Message); Finally, to print the line number where the error is System.Console.WriteLine(dbz.StackTrace);

Source: msdn.microsoft.com

Categories: C #, visualstudio Tags: ,